我对SQL真的不太满意,我只想编写一个在图表中显示一些日志数据的查询。
我有一个SQL Server表,我记录了对Web服务的请求。
ID RequestedFunction RequestDateTime
1 'Confirm()' 2010-12-15 13:27:01.234
2 'Register()' 2010-12-16 12:27:00.678
3 'Confirm()' 2010-12-16 21:00:05.456
现在,我想编写一个查询,返回每天按RequestedFunction分组的请求数;返回给我一个像这样的数据集。
Day ConfirmFunctionRequests RegisterFunctionRequests
15 1 0
16 1 1
这可能吗?到目前为止我能想到的就是这样的事情,
;WITH CTE AS
(
SELECT id,
[Day] = CAST(day(requestDateTime) AS INT),
RequestedFunction
FROM [Log]
WHERE month(RequestDateTime)=12 AND
year(RequestDateTime)=2010
)
SELECT [Day],COUNT(ID) AS [#Requests] FROM CTE GROUP BY [Day]
返回每天的请求数,而不区分不同类型的请求。如何根据“RequestedFunction”中的值编写一个将请求计入两个不同列的查询?
答案 0 :(得分:2)
这可以使用PIVOT完成,但快速简单的解决方案就像
DECLARE @Log TABLE(
ID INT,
RequestedFunction VARCHAR(50),
RequestDateTime DATETIME
)
INSERT INTO @Log SELECT 1,'Confirm()','2010-12-15 13:27:01.234'
INSERT INTO @Log SELECT 2,'Register()','2010-12-16 12:27:00.678'
INSERT INTO @Log SELECT 3,'Confirm()','2010-12-16 21:00:05.456'
SELECT DATEADD(dd,0, DATEDIFF(dd,0,RequestDateTime)) DayValue,
SUM(
CASE
WHEN RequestedFunction = 'Confirm()' THEN 1
ELSE 0
END
) ConfirmFunctionRequests,
SUM(
CASE
WHEN RequestedFunction = 'Register()' THEN 1
ELSE 0
END
)RegisterFunctionRequests
FROM @Log
GROUP BY DATEADD(dd,0, DATEDIFF(dd,0,RequestDateTime))