您好我正在尝试编写一个查询,该查询将返回客户的每日客户记录数(过去7天)
给出一个包含以下重要字段的表
ClientId, ProcessTime,
id喜欢使用clientId生成一个表,最后7天生成列标题0 - 7(包括今天)以及当天处理的记录
ClientId, 0, 1, 2, 3, 4, 5, 6, 7
我提出了以下查询,让我接近
Select ClientId, Count(Id) as [Count], max(DATEDIFF(DAY,ProcessTime,GETDATE())) as [Day]
from CallRecords
WHERE DATEDIFF(DAY,ProcessTime,GETDATE()) <= 7
group by ClientId, Dateadd(day, Datediff(day, 0, ProcessTime), 0)
order by 1, 2
产生
ClientId Count Day
1 60 0
1 4707 1
1 11613 2
然而我,我不知道如何将这些结果操作为一种格式,我得到一个客户列表和最后7天的结果作为列
有什么想法吗?
答案 0 :(得分:1)
SELECT ClientID
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 1 THEN 1 ELSE NULL END) AS [Sunday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 2 THEN 1 ELSE NULL END) AS [Monday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 3 THEN 1 ELSE NULL END) AS [Tuesday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 4 THEN 1 ELSE NULL END) AS [Wednesday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 5 THEN 1 ELSE NULL END) AS [Thursday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 6 THEN 1 ELSE NULL END) AS [Friday]
,COUNT(CASE WHEN DATEPART(WEEKDAY,ProcessTime) = 7 THEN 1 ELSE NULL END) AS [Saturday]
FROM CallRecords
WHERE ProcessTime >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 7, 0)
GROUP BY ClientID
答案 1 :(得分:0)
你想要的是pivot,SQLServer本身支持:
select ClientId, [0], [1], [2], [3], [4], [5], [6], [7]
from (select ClientId, DATEDIFF(DAY,ProcessTime,GETDATE()) days
from CallRecords
where DATEDIFF(DAY,ProcessTime,GETDATE()) <= 7) t
pivot (count(days) for days in ([0], [1], [2], [3], [4], [5], [6], [7])) pt
答案 2 :(得分:0)
Pivot是实现此方案的方法。以下是Microsofts数据透视文档Microsoft PIVOT的链接。要查找星期几,您应使用DatePart函数Microsoft DatePart Function
select ClientId as 'Client', [1], [2], [3], [4], [5], [6], [7] from (
select ClientId, Id, CAST(DatePart(dw,ProcessTime) as int) as [DayOfWeek]
from CallRecords
) as SourceTable
PIVOT (
COUNT(Id)
FOR [DayOfWeek] IN ([1], [2], [3], [4], [5], [6], [7])
) as pvt