【问题标题】:Dynamically Creating Column Counts Per Day of Month每月动态创建列计数
【发布时间】:2014-01-17 21:30:12
【问题描述】:

好的,所以我有这个查询来查找每天的类型数量,如下所示。 (此处由 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

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

【问题讨论】:

  • 如果动态创建列,则需要动态创建计数的总和。这可以使用列上的聚合和group by grouping sets 命名法来完成。
  • 谢谢你!我会检查一下。 :)
  • 我认为 Grouping/Rollup 的内容比我在当月的某一天尝试做的事情有点提前。我想我只需要创建一个变量或函数来替换某个给定月份值的每一天的 MyDate 值。例如,这应该与为 10 月的每一天手动运行上述总和相同。我已经为 10 月编写了每一天的内联...只是想知道是否有人有办法使用单个变量/函数值或行自动插入每月的每一天。

标签: sql oracle-sqldeveloper dynamic-columns


【解决方案1】:

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

 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 月等时间运行它,我只需更改顶部的变量并运行查询。这就是我一直在寻找的;但是,我仍然想知道是否可以动态生成列,但我越看越觉得需要数据透视表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    相关资源
    最近更新 更多