Netezza日期范围

时间:2019-01-29 11:20:24

标签: sql netezza

我想解决一个问题,以减少特定查询中的体力劳动。希望我能正确理解这句话。

在Netezza中,我想生成一个(date)值并针对指定的每个不同值运行查询。 我想做的是将所有联合替换为一个查询

SELECT DISTINCT COUNT(DISTINCT a.x) AS NO_OF_X, a.column1, 'JAN 2019'
FROM my_table a
WHERE 1=1  
AND current_date BETWEEN a.date_from and a.date_to

GROUP BY 2,3  

UNION ALL

SELECT DISTINCT COUNT(DISTINCT a.x) AS NO_OF_X, a.column1, 'DEC 2018'
FROM my_table a
WHERE 1=1  
AND '2018-12-31' BETWEEN a.date_from and a.date_to
GROUP BY 2,3

UNION ALL

SELECT DISTINCT COUNT(DISTINCT a.x) AS NO_OF_X, a.column1, 'NOV 2018'
FROM my_table a
WHERE 1=1  
AND '2018-11-30' BETWEEN a.date_from and a.date_to
GROUP BY 2,3 

我想做的就是这样

SELECT DISTINCT COUNT(DISTINCT a.x) AS NO_OF_X, a.column1, last_day( date ) as "MONTH"
FROM my_table a
WHERE 1=1  
AND /*run the query for all last_days in a range */ 
GROUP BY 2,3 

这可能吗?试图进行CTE,但获得每个月最后一个特定日期的结果非常重要,因为我们的数据仓库的设计旨在为每个交易存储不同的时间片等。我只想获得特定时间片上具有时间片的交易last_day()。

干杯。

1 个答案:

答案 0 :(得分:1)

您需要生成日期列表。这是一种方法:

select to_char(m.dte, 'MMM YYYY'), t.column1,
       count(distinct a.x) AS NO_OF_X
from (SELECT current_date as dte UNION ALL
      SELECT date_trunc('month', current_date) - interval '1 day' as dte UNION ALL
      SELECT date_trunc('month', current_date) - interval '1 day' - interval '1 month' as dte UNION ALL
      SELECT date_trunc('month', current_date) - interval '1 day' - interval '2 month' as dte
      ) m left join
      my_table t
where m.dte between t.date_from and t.date_to
group by to_char(m.dte, 'MMM YYYY'), t.column1
order by min(m.dte), t.column1;