在间隔中计算记录,不同表格,分组依据,时间戳记

时间:2013-06-19 00:02:11

标签: sql sql-server

我有这个SQL示例(还有更多内容,只是对表的附加查询,相同的结构),它给出了一个表列表,以及那些UpdatedOn字段是唯一值,表示执行了“单独”编辑,而不是使用更新语句进行编辑,更改具有相同时间戳的多个记录。这个SQL效果很好。但是,我想更进一步。我希望以数月为单位表示计数,并且优先计算年份,因此结果会增长并累积。这是我的SQL:

select 'BuriedSplice' as [Table], count(*) as Changes from BuriedSplice where UpdatedOn in 
  (select UpdatedOn from BuriedSplice group by UpdatedOn having count(*) = 1)
    union
select 'CableCoil' as [Table], count(*) as Changes from CableCoil where UpdatedOn in 
  (select UpdatedOn from CableCoil group by UpdatedOn having count(*) = 1)

结果是:

Table           Changes
BuriedSplice    53
CableCoil       14

我想看到的是:

Table           1/2013 Changes  2/2013 Changes  3/2013 Changes
BuriedSplice    12              17              24 
CableCoil       4               3               7

或者喜欢:

January 2013
Table           Changes
BuriedSplice    12 
CableCoil       4

February 2013
Table           Changes
BuriedSplice    17 
CableCoil       3

March 2013
Table           Changes
BuriedSplice    24 
CableCoil       7

提前谢谢。

1 个答案:

答案 0 :(得分:1)

我将建议稍微不同的格式,标题如下:

Year   Month    BuriedSpice    CableCoil

原因是年/月可能有很多行。但进入查询的表 - 即使超过2 - 是固定的。所有SQL查询都有固定数量的列,因此这种格式是有意义的。

以下使用union all查询采用此方法:

select yr, mon, sum(BuriedSpice) as BuriedSplice, sum(CableCoil) as CableCoil
from ((select year(UpdatedOn) as yr, month(UpdatedOn) as mon, count(*) as BuriedSplice, 0 as CableCoil
       from (select UpdatedOn
             from BuriedSplice
             group by UpdatedOn
             having count(*) = 1
            ) bs
       group by year(UpdatedOn), month(UpdatedOn)
      ) union all
      (select year(UpdatedOn) as yr, month(UpdatedOn) as mon, 0, count(*)
       from (select UpdatedOn
             from CableCoil
             group by UpdatedOn
             having count(*) = 1
            ) cc
       group by year(UpdatedOn), month(UpdatedOn)
      )
     ) t
group by yr, mon