选择具有多个子查询的查询(Netezza SQL)

问题描述 投票:0回答:1

我正在尝试创建一个报告,在3个时间段内计算:上个月,去年的那个月和今年的年份。

我之前使用了3个单独的查询,同时切换where子句,但我希望能够将所有3个组合成一个查询。

我已尝试过案例陈述,但似乎无法让它发挥作用。仅供参考,app_dateYYYY-MM-DD

Select count(application_id)
from application_data a
where to_char(app_date, 'YYYYMM' = to_char(current_date, 'YYYYMM')-1
--where to_char(app_date, 'YYYYMM' = to_char(current_date, 'YYYYMM')-101
--where to_char(app_date, 'YYYY') = to_char(current_date, 'YYYY') and to_char(app_date, 'YYYYMM') <> to_char(current_date, 'YYYYMM')

样本数据:

App_ID          App_date  
123519          2018-02-17  
123521          2018-02-18  
123522          2018-02-19  
123523          2018-02-23  
123518          2019-01-15  
123546          2019-02-21  
123547          2019-02-22  
123548          2019-02-15  
123542          2019-02-02  

期望的结果:

LastMonth      YTD       YoY  
4               5         4
sql netezza
1个回答
1
投票

我想你想要条件聚合:

Select sum(case when to_char(app_date, 'YYYYMM' = to_char(current_date, 'YYYYMM')-1 then 1 else 0 end),
       sum(case to_char(app_date, 'YYYYMM' = to_char(current_date, 'YYYYMM')-101 when then 1 else 0 end),
       sum(case when to_char(app_date, 'YYYY') = to_char(current_date, 'YYYY') and to_char(app_date, 'YYYYMM') <> to_char(current_date, 'YYYYMM') then 1 else 0 end)
from application_data a
© www.soinside.com 2019 - 2024. All rights reserved.