首页 > 解决方案 > 条件在不同行和列中时的 CASE 语句

问题描述

DB小提琴

CREATE TABLE sales (
    campaign VARCHAR(255),
    event_type VARCHAR(255),
    event_date VARCHAR(255),
    quantity VARCHAR(255)
);

INSERT INTO sales
(campaign, event_type, event_date, quantity)
VALUES 
("C001", "buy", "2019-05-08", "500"),
("C001", "sale", "2019-04-20", "400"),

("C002", "buy", "2019-06-07", "800"),
("C002", "sale", "2019-06-15", "900"),

("C003", "buy", "2020-02-23", "700"),
("C003", "sale", "2020-03-17", "300"),

("C004", "buy", "2020-04-05", "200"),
("C004", "sale", "2020-03-17", "600");

该表显示event_types (buy, sell)和对应的quantities每个campaign


现在,我想运行一个query检查以下内容:

a)event_dateevent_type buy>event_dateevent_type sell
b)quantityevent_type buy>quantityevent_type sell

结果应如下所示:

campaign     Check_Date     Check_Quantity
C001            Error            OK
C002            OK              Error
C004            OK              Error

我想我需要以CASE某种方式接受这样的声明:

SELECT
campaign, 
(CASE WHEN event_date of buy > event_date of sale THEN "Error" ELSE "OK") AS Check_Date,
(CASE WHEN quantity of buy > quantity of sale THEN  "Error" ELSE "OK") AS Check_Quantity
quantity
FROM sales;

标签: mysqlsqldategroup-bypivot

解决方案


您想跨行比较值,因此这建议进行聚合。然后,您可以使用case表达式实现逻辑:

select
    campaign, 
    case when 
        max(case when event_type = 'buy' then event_date end) 
            > max(case when event_type = 'sale' then event_date end)
            then 'OK'
            else 'Error'
    end check_date,
    case when 
        max(case when event_type = 'buy' then quantity end) 
            > max(case when event_type = 'sale' then quantity end)
            then 'OK'
            else 'Error'
    end check_date
from sales
group by campaign;

您的 DB Fiddle中,这会产生:

活动 | 检查日期 | 检查日期
:------- | :--------- | :---------
C001 | 好的 | 好的        
C002 | 错误 | 错误     
C003 | 错误 | 好的        
C004 | 好的 | 错误     

推荐阅读