1

我有这个 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

先感谢您。

4

1 回答 1

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
于 2013-06-19T00:09:42.873 回答