mysql - 条件在不同行和列中时的 CASE 语句
问题描述
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_date
为event_type
buy
>event_date
为event_type
sell
b)quantity
为event_type
buy
>quantity
为event_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;
解决方案
您想跨行比较值,因此这建议进行聚合。然后,您可以使用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 | 好的 | 错误
推荐阅读
- babel-core - 模块构建失败:错误:在 Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15) 处找不到模块“babel-core”
- reactjs - if else 多于一个日期结果
- c - 为什么在我输入另一个输入之后我的代码不打印?
- jquery - 如何更改 snap.svg 中的文本
- javascript - 如何检查元素是否有效 JSX
- python - Open CV 中的关键特征跟踪
- maven - maven 版本:设置不采用 version.properties 的版本
- sql - 按索引表排序(关联数组)
- java - 任何服务类都不应使用 Java.util.date
- azure - 如何在 azure datafactory 复制活动中将会话参数传递给 Oracle .. 在 Oracle Linkedservice