计算sql中group by子句每月的记录数

时间:2013-11-07 11:26:48

标签: sql

我需要每个月都有一个报告,我有城镇,街道名称,t_number,t_date_time_issued,其中t_number是在每个城镇发行的门票。我现在需要每年每月发行多少张票,这个月的总票数是去年的最后一年有什么差别 - 本月总发行票数。我绑了以下但是没有运气。

SELECT [Town],
      [Site Name],

  SUM(CASE datepart(month,t_date_time_issued) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,t_date_time_issued) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    [VCS].[dbo].[manual issued sites]  as a 

  inner join icps.dbo.tickets as b on
  b.[t_street_name]COLLATE DATABASE_DEFAULT  = a.[Town] COLLATE DATABASE_DEFAULT and
  b.[t_zone_name]COLLATE DATABASE_DEFAULT  = a.[Site Name] COLLATE DATABASE_DEFAULT 

where year(t_date_time_issued) = '2012' 
  GROUP BY  month(t_date_time_issued),town,sitename

   order by town


but i need something like  
town sitename  jan feb march april june july..... total
abc  bbb         10 10  15   25     30   45       xyz..
ybb  jjjj        25  14  45  25  312  455    ....uuu 
----------

上面的查询就是这样做的....

Town    Site Name   January February    March   April   May June    July    August  September   October November    December    TOTAL
Bawtry  Market Hill 155 0   0   0   0   0   0   0   0   0   0   0   155
Bawtry  Market Hill 0   194 0   0   0   0   0   0   0   0   0   0   194
Bawtry  Market Hill 0   0   144 0   0   0   0   0   0   0   0   0   144
Bawtry  Market Hill 0   0   0   114 0   0   0   0   0   0   0   0   114
Formby  The Cloisters   0   0   0   0   0   0   0   0   0   0   0   36  36
Kidderminster   Crossley Retail Park    27  0   0   0   0   0   0   0   0   0   0   0   27
Kidderminster   Crossley Retail Park    0   15  0   0   0   0   0   0   0   0   0   0   15
Kidderminster   Crossley Retail Park    0   0   20  0   0   0   0   0   0   0   0   0   20

0 个答案:

没有答案