选择不同的计数使用量除以月份

时间:2015-05-28 13:09:29

标签: sql sql-server-2012 distinct

我有一张表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

我知道我可以使用此查询在一个月内获得许可证总数:

SELECT vlu.[Userkey],
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,
COUNT(CASE WHEN MONTH = 4 THEN 1 END) as APR,
COUNT(CASE WHEN MONTH = 5 THEN 1 END) as MAY,
COUNT(CASE WHEN MONTH = 6 THEN 1 END) as JUN,
COUNT(CASE WHEN MONTH = 7 THEN 1 END) as JUL,
COUNT(CASE WHEN MONTH = 8 THEN 1 END) as AUG,
COUNT(CASE WHEN MONTH = 9 THEN 1 END) as SEP,
COUNT(CASE WHEN MONTH = 10 THEN 1 END) as OCT,
COUNT(CASE WHEN MONTH = 11 THEN 1 END) as NOV,
COUNT(CASE WHEN MONTH = 12 THEN 1 END) as DEC
FROM license_usage vlu 
     CROSS APPLY (SELECT MONTH(vlu.EndDate)) AS CA(Month)
WHERE vlu.[EndDate] >='2015-01-01'
      AND vlu.[EndDate] < '2016-01-01'
GROUP BY vlu.[Userkey]

如何让它返回我的结果?

实施例: http://sqlfiddle.com/#!3/be0b4/1

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望每个用户每月最多使用一天。您想要的基本数据是:

select UserKey, month(license_usage) as mm, day(license_usage) as dd,
       count(distinct license) as cnt
from license_usage vlu
where vlu.EndDate] >= '2015-01-01' and vlu.EndDate < '2016-01-01'
group by UserKey, month(license_usage), day(license_usage);

然后您可以通过多种方式对其进行调整,例如使用条件聚合:

select UserKey,
       max(case when mm = 1 then cnt else 0 end) as Jan,
       . . .
from (select UserKey, month(license_usage) as mm, day(license_usage) as dd,
             count(distinct license) as cnt
      from license_usage vlu
      where vlu.EndDate] >= '2015-01-01' AND vlu.EndDate < '2016-01-01'
      group by UserKey, month(license_usage), day(license_usage)
     ) umd
group by UserKey;

CROSS APPLY是一种有趣的方法,但我无法想到获取此信息的更简单方法。

答案 1 :(得分:0)

通过在Count(*)

上使用distinct来获得它
select umd.pbrUserkey,
       max(case when mm = 1 then cnt else 0 end) as Jan,
       max(case when mm = 2 then cnt else 0 end) as Feb,
       max(case when mm = 3 then cnt else 0 end) as Mar,
       max(case when mm = 4 then cnt else 0 end) as Apr,
       max(case when mm = 5 then cnt else 0 end) as May
from (select vluk.pbrUserkey, month(vluk.EndDate) as mm, day(vluk.EndDate) as dd,
             count(distinct vluk.idPackage) as cnt
      from [license_usage] as vluk
      where vluk.[EndDate] >= '2015-01-01' AND vluk.[EndDate] < '2016-01-01'
      group by vluk.Userkey, month(vluk.EndDate), day(vluk.EndDate)
     ) umd
group by umd.Userkey;