将多个 select 查询更改为 CTE 查询

Changing multiple select query into CTE query

我想将这个特别简单的 select 查询更改为 CTE 以优化它,因为这个简单的三个 select 查询需要 4 分钟左右,所以我想减少执行时间通过将其转换为 CTE 查询。

select sum(AMOUNT) usd from data where status IN ('ACCEPTED','REJECTED','CANCELLED') and date between '01-SEP-18' and '30-NOV-18' 
UNION 
select sum(AMOUNT) usd from data where status IN ('ACCEPTED','REJECTED','CANCELLED') and date between '01-NOV-18' and '31-JAN-19' 
UNION 
select sum(AMOUNT) usd from data where status IN ('ACCEPTED','REJECTED','CANCELLED') and date between '01-FEB-19' and '30-APR-19' 
ORDER BY usd DESC ;

预期的结果应该是一栏显示三个查询的结果,即本次查询金额的usd之和。

示例:

USD
100 (timeline 1)
200 (timeline 2)
300 (timeline 3)

我试过的那个: 你能用 sum 而不是 count 来转换这个 CTE 查询吗?

WITH cte AS (
    SELECT
        COUNT(CASE WHEN status_date BETWEEN '2018-11-01' AND '2019-01-31' THEN 1 END) AS cnt1,
        COUNT(CASE WHEN status_date BETWEEN '2019-02-01' AND '2019-04-30' THEN 1 END) AS cnt2,
        COUNT(CASE WHEN status_date BETWEEN '2019-05-01' AND '2019-07-31' THEN 1 END) AS cnt3
    FROM data
    WHERE status IN ('ACCEPTED', 'REJECTED', 'CANCELLED')
)

SELECT cnt1 FROM cte
UNION ALL
SELECT cnt2 FROM cte
UNION ALL
SELECT cnt3 FROM cte;

我猜你不希望时间线重叠,所以:

select (case when date between '01-SEP-18' and '30-NOV-18' then 'timeline1'
             when date between '01-DEC-18' and '31-JAN-19' then 'timeline2'
             when date between '01-FEB-19' and '30-APR-19' then 'timeline3'
        end), sum(AMOUNT) as usd
from data
where status IN ('ACCEPTED','REJECTED','CANCELLED') and 
     date between '01-SEP-18' and '30-APR-19'
group by (case when date between '01-SEP-18' and '30-NOV-18' then 'timeline1'
               when date between '01-DEC-18' and '31-JAN-19' then 'timeline2'
               when date between '01-FEB-19' and '30-APR-19' then 'timeline3'
        end)
order   by usd desc;

如果这样做,单独的列可能更简单:

select sum(case when date >= date '2018-09-01' and date < date '2018-12-01' then amount end) as usd_timeline1,
       sum(case when date >= date '2018-11-01' and date < date '2019-02-01' then amount end) as usd_timeline2
       sum(case when date >= date '2019-02-01' and date '2019-05-01' then amount end) as usd_timeline3
from data
where status IN ('ACCEPTED','REJECTED','CANCELLED') and 
      date >= date '2018-09-01' and date < date '2019-05-01'
order by usd desc;

请注意,这使用了使用 ISO 标准 YYYY-MM-DD 格式和 date 关键字的日期常量。