使用SQL查询计算每个月的票数

时间:2014-04-06 08:40:27

标签: sql sql-server count group-by distinct

我有一个名为Ticket的表,其中包含超过1000条记录:

TicketNo  TicketDate  StateID 
1         01/01/2013  100
2         05/01/2013  100
3         09/01/2013  101
4         15/01/2013  101
5         17/01/2013  102
6         01/02/2013  100
7         05/02/2013  100
8         08/02/2013  102
9         22/02/2013  103
10        28/02/2013  103
...

我想显示一年中每个州每个StateId的门票数量,例如:

StateID  FirstMonthCount  SecondMonthCount  Third...
100      2                2
101      2                0
102      1                1
103      0                2
...

我尝试编写查询但不能在每个月显示结果

  SELECT StateID, Count(StateID) AS Count, From Ticket
  WHERE TicketDate >= '01/01/2013' AND TicketDate <= '31/01/2013' 
  Group By StateID Order By StateID

1 个答案:

答案 0 :(得分:1)

您需要PIVOT这样的表:

SELECT
   StateID, [1] as FirstMonthCount, [2] as SecondMonthCount, ...
FROM
   (
      SELECT DATEPART(m, TicketDate) TheMonth, StateID 
      FROM tbl
      WHERE TicketDate >= '01/01/2013'
        AND TicketDate <= '31/12/2013'
   ) as src
PIVOT
   (
       COUNT(TheMonth)
       FOR TheMonth IN ([1], [2], ..., [12])
   ) as pvt

<强> SQL FIDDLE DEMO