繁体   English   中英

将两个SQL查询的结果与UNION合并并融合

[英]Combine and fuse the results of two SQL queries with UNION

我正在编写两个单独的SQL查询以获取两个不同日期的数据,如下所示:

SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin
FROM table_a
WHERE day = '2019-08-09'
GROUP BY number

SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin
FROM table_a
WHERE day = '2018-08-10'
GROUP BY number

我试着像这样融合它们,以便从两个不同的日期获得一行中相同数字的结果:

SELECT number, sum(sales) as sales, sum(discount) sa discount, sum(margin) as margin, 0 as sales_n1, 0 as discount_n1, 0 as margin_n1
FROM table_a
WHERE day = '2019-08-09'
GROUP BY number
UNION
SELECT number, 0 as sales, 0 as discount, 0 as margin, sum(sales_n1) as sales_n1, sum(discount_n1) as discount_n1, sum(margin_n1) as margin_n1
FROM table_a
WHERE day = '2018-08-10'
GROUP BY number

但这没有用,因为我以相同的方式获得了第一个查询的行,并且定义为零的列为零,然后是第二个查询的列。

我该如何纠正它以获得所需的输出?

使用条件聚合:

SELECT number,
       sum(case when day = '2019-08-09' then sales end) as sales_20190809,
       sum(case when day = '2019-08-09' then discount end) sa discount, sum(margin) as margin_20190810,
       sum(case when day = '2019-08-10' then sales end) as sales_20190809,
       sum(case when day = '2019-08-10' then discount end) sa discount, sum(margin) as margin_20190810
FROM table_a
WHERE day IN ('2019-08-09', '2019-08-10')
GROUP BY number;

如果您希望数字位于不同的行中(您似乎不需要),请使用聚合:

SELECT day, number, sum(sales) as sales, sum(discount) as discount, sum(margin) as margin
FROM table_a
WHERE day IN ('2019-08-09', '2019-08-10')
GROUP BY day, number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM