选择计数使用量除以月

时间:2015-05-25 20:03:15

标签: sql sql-server sql-server-2012

我确实有一个表license_Usage,其工作方式就像一天中许可证使用情况的记录一样

ID   User        license    date
1    1            A        22/1/2015
2    1            A        23/1/2015
3    1            B        23/1/2015
4    1            A        24/1/2015
5    2            A        22/2/2015
6    2            A        23/2/2015
7    1            B        23/2/2015

如果我想计算一个月内用户使用的许可证数量,结果应如下所示:

   User          Jan           Feb   
    1             2             1        ...
    2             0             2

我怎样设法做到?

1 个答案:

答案 0 :(得分:2)

您需要PIVOT或交叉表查询。 e.g。

SELECT [User],
       COUNT(CASE WHEN Month = 1 THEN 1 END) AS Jan,
       COUNT(CASE WHEN Month = 2 THEN 1 END) AS Feb,
       COUNT(CASE WHEN Month = 3 THEN 1 END) AS Mar
       /*TODO - Fill in other 9 months using above pattern*/
FROM   [license]
       CROSS APPLY (SELECT MONTH([date])) AS CA(Month)
WHERE  [date] >= '20150101'
       AND [date] < '20160101'
       AND [license] = 'A'
GROUP  BY [User] 

SQL Fiddle