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

时间:2019-08-09 12:57:37

标签: sql 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

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

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

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

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