按年份+月份的SQL组,但也可以获得几个月的w / o记录

时间:2014-02-05 13:35:45

标签: sql db2

我想按文字分组表的内容,然后按年+月分组,并将计数加起来:


+-------------+---------+----------+----------+
|    TEXT     | T1_YEAR | T1_MONTH | T1_COUNT |
+-------------+---------+----------+----------+
| First Text  |    2013 |        1 |        1 |
| First Text  |    2013 |        2 |        1 |
| First Text  |    2013 |        3 |        1 |
| First Text  |    2013 |        5 |        1 |
| First Text  |    2013 |        6 |        3 |
| First Text  |    2013 |        7 |        1 |
| First Text  |    2013 |        8 |        3 |
| First Text  |    2013 |        9 |        1 |
| First Text  |    2013 |       10 |        2 |
| Second Text |    2013 |        1 |        2 |
| Second Text |    2013 |        2 |        5 |
| Second Text |    2013 |        3 |        8 |
| Second Text |    2013 |        4 |        5 |
| Second Text |    2013 |        5 |       23 |
| Second Text |    2013 |        6 |        9 |
| Second Text |    2013 |        7 |       27 |
+-------------+---------+----------+----------+
select 
  table1.TEXT text, 
  year(table1.timestamp) t1_year, 
  month(table1.timestamp) t1_month, 
  count (*) as t1_count
from table1
group by 
  table1.TEXT, 
  year(table1.timestamp), 
  month(table1.timestamp)
with ur;

现在我还想在结果表中输入缺少月数的条目0。

我已经阅读了其他关于临时表的帖子,但我还没弄清楚如何让它工作。

WITH DATERANGE(LEVEL, TEMP_DATE) AS (
  SELECT 1, CURRENT DATE - 5 MONTHS
    FROM SYSIBM.SYSDUMMY1
  UNION ALL SELECT LEVEL + 1, TEMP_DATE + 1 MONTH
    FROM DATERANGE
    WHERE LEVEL < 1000 AND TEMP_DATE < CURRENT DATE - 1 MONTH
) SELECT TEMP_DATE FROM DATERANGE;

临时日期表:

+------------+
| TEMP_DATE  |
+------------+
| 2013-09-05 |
| 2013-10-05 |
| 2013-11-05 |
| 2013-12-05 |
| 2014-01-05 |
+------------+

我怎样才能实现这一目标?我正在使用DB2。

1 个答案:

答案 0 :(得分:0)

我会创建一个具有相同类型值(年和月)的临时表。然后你可以从那里外连接到你的数据表:

select
dt.theyear,
dt.themonth,
sum(t1_count)

from
DateTable DT
left outer join table1 t1
  on dt.theyear = t1.t1_year
  and dt.theMOnth = t1.t1_month
group by
dt.theyear,
dt.themonth

这是一个SQL小提琴示例(SQL Server,因为它们没有DB2,但它应该转换得很好): SQL FIddle