Postgres - 如何将两个单独查询的结果合并到同一列中

时间:2018-06-15 17:37:23

标签: sql postgresql

我使用CTE从两个不同的日期拉出相同的列,因为我需要提取每个季度的最新日期。所以查询看起来像这样:

WITH Q1 AS
(
SELECT date, region, revenue
FROM sales
WHERE date = (SELECT MAX(date) from sales WHERE date between date_trunc('quarter', CURRENT_DATE)::date - interval '3 months' AND DATE_TRUNC('quarter', CURRENT_DATE)::date - interval '1 day')
)
, Q2 AS
(
SELECT date, region, revenue
FROM sales
WHERE date = (SELECT MAX(date) FROM sales WHERE date BETWEEN DATE_TRUNC('quarter', CURRENT_DATE)::date AND DATE_TRUNC('quarter', CURRENT_DATE)::date + interval '3 months')
)
SELECT q1.date, q1.region, q1.sales, q2.date, q2.region, q2.sales
FROM Q1
INNER JOIN Q2
USING (region)

哪个输出了我的预期:

date       | region     | sales   | date       | region     | sales
-----------|------------|---------|------------|------------|----------
2018-03-31 | US - West  | 2387598 | 2018-06-14 | US - West  | 2389075
2018-03-31 | US - East  | 3098527 | 2018-06-14 | US - East  | 3095735
2018-03-31 | US - South | 1029745 | 2018-06-14 | US - South | 1023754

但是,由于它们具有相同的列,我希望它们堆叠为行而不是额外的列。我希望它看起来像这样:

date       | region     | sales   
-----------|------------|---------
2018-03-31 | US - West  | 2387598 
2018-03-31 | US - East  | 3098527 
2018-03-31 | US - South | 1029745 
2018-06-14 | US - West  | 2389075
2018-06-14 | US - East  | 3095735
2018-06-14 | US - South | 1023754

我知道我通过加入地区做错了,但我不知道如果没有它我将如何合并CTE。

1 个答案:

答案 0 :(得分:1)

使用union all

SELECT q1.date, q1.region, q1.sales
FROM Q1
UNION ALL
SELECT q2.date, q2.region, q2.sales
FROM Q2;

或者,您可以免除CTE并使用OR

SELECT date, region, revenue
FROM sales
WHERE date = (SELECT MAX(date) from sales WHERE date between date_trunc('quarter', CURRENT_DATE)::date - interval '3 months' AND DATE_TRUNC('quarter', CURRENT_DATE)::date - interval '1 day') OR
      date = (SELECT MAX(date) FROM sales WHERE date BETWEEN DATE_TRUNC('quarter', CURRENT_DATE)::date AND DATE_TRUNC('quarter', CURRENT_DATE)::date + interval '3 months');