每月动态创建列计数

时间:2014-01-17 21:30:12

标签: sql oracle-sqldeveloper dynamic-columns

好的,所以我有这个查询来查找每天的类型数量,如下所示。 (由MarkD提供Counting Items/Rows in DB as Columns Grouped by Another Column

 select type,
           sum(case when MyDate = '' then 1 else 0 end) as "10/1",
           sum(case when MyDate = '' then 1 else 0 end) as "10/2
           ...etc
 from MyTabe
 group by type

但是,我想动态创建日期列并为每列生成计数,否则我最终会为每个月的每一天手动添加新列。

1 个答案:

答案 0 :(得分:0)

我想获得我想要的输出的最佳方法是执行以下操作:

 define startDate = to_date('2013-10-01', 'yyyy-mm-dd')
 select type,
       sum(case when MyDate = &&startDate then 1 else 0 end) as "1"
       , sum(case when MyDate = &&startDate +1 then 1 else 0 end) as "2"
       , sum(case when MyDate = &&startDate +2 then 1 else 0 end) as "3"
       , sum(case when MyDate = &&startDate +3 then 1 else 0 end) as "4"
       ...etc for as many days of current month I am running
       , sum(case when MyDate = &&startDate +29 then 1 else 0 end) as "30"   
       , sum(case when MyDate = &&startDate +30 then 1 else 0 end) as "31"--This would be commented out for Nov  
 from MyTabe
 group by type
 order by type
 ;

这样,如果我想在11月,12月,1月等运行它,我可以只更改顶部的变量并运行查询。这就是我所寻找的;但是,我仍然想知道是否可以动态生成列,但我看的越多,我认为需要一个数据透视表就越多。

相关问题