Netezza 日期范围

Netezza range of dates

我想解决一个问题以减少特定查询中的人工劳动。希望我能用正确的措辞来理解。

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

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().

干杯。

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

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;