我需要计算全年每个月每个用户的登录次数,该如何处理,我认为Pivoting可能是答案,但似乎无法弄清楚如何编写查询。
我有2列,一列与userID,另一列与datetime。
如果我执行select count(Start) , userID from LoginTable where Start between '2018-01-01' and '2018-12-31' group by userID
,则可以得到用户全年的登录次数,但是如何将结果分开以具有每月的登录时间呢?
这是桌子
我想在新列中显示月份,将月份1排至1月列,将月份2排至2月列等
答案 0 :(得分:1)
这是您想要的吗?
declare @LoginTable table (UserId int, [Start] datetime)
insert into @LoginTable (UserId, [Start])
select 1, '1 jan 2018'
union all select 2, '1 jan 2018'
union all select 2, '1 jan 2018'
union all select 1, '1 feb 2018'
union all select 2, '1 feb 2018'
union all select 1, '1 mar 2018'
union all select 2, '1 mar 2018'
union all select 1, '1 apr 2018'
union all select 2, '1 apr 2018'
union all select 1, '1 may 2018'
union all select 2, '1 may 2018'
union all select 1, '1 jun 2018'
union all select 2, '1 jun 2018'
union all select 1, '1 jul 2018'
union all select 2, '1 jul 2018'
union all select 1, '1 aug 2018'
union all select 2, '1 aug 2018'
union all select 1, '1 sep 2018'
union all select 2, '1 sep 2018'
union all select 1, '1 oct 2018'
union all select 2, '1 oct 2018'
union all select 1, '1 nov 2018'
union all select 2, '1 nov 2018'
union all select 1, '1 dec 2018'
union all select 2, '1 dec 2018'
select UserId, [Year], Y.*
from (
select UserId, datepart(year,[Start]) [Year], substring(datename(month,[Start]), 1, 3) [Month], count(*) num
from @LoginTable
group by UserId, datepart(year,[Start]), substring(datename(month,[Start]), 1, 3)
) X
pivot (
sum(num)
for [Month] in ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])
) Y
PS-请在将来发布这样的问题,即带有示例数据和可以复制和粘贴的查询尝试。