我想要一张
的表格1> requestTime 2> NumberOfSessionsInLast15minutes
如何编写查询以获取requestTime列所在的表 将是相同的,NumberOfSessions列将是会话的总和 在最后15分钟
示例:
2012-06-06 00:12:00.0000的会话数量应该是 是2012-06-06 00:12:00.0000和(2012-06-06)之间的会话总和 00:12:00.0000) - 15分钟。
答案 0 :(得分:2)
您可以使用子查询来检索会话数:
select s1.requesttime
, (
select sum(NumberOfSessions)
from sessions s2
where dateadd(minute, -15, s1.requesttime) < s2.requesttime
and s2.requesttime <= s1.requesttime
) as TotalNumberOfSessions
from sessions s1
答案 1 :(得分:1)
DECLARE
@reportTime DATETIME
SELECT
@reportTime = '2012-06-06 00:12'
SELECT
@reportTime,
SUM(NumberOfSessions)
FROM
yourTable
WHERE
requestTime > DATEADD(minute, -15, @reportTime)
AND requestTime <= @reportTime
根据您的需求和数据的确切行为,混合并匹配>=
,>
,<
和<=
。
(通常15分钟的窗口为>= 00:00 AND < 00:15
,但您的定义与此略有不同。)
如果您想要源表中的所有记录......
SELECT
base.requestTime,
SUM(history.NumberOfSessions)
FROM
yourTable AS base
INNER JOIN
yourTable AS history
ON history.requestTime > DATEADD(minute, -15, base.requestTime)
AND history.requestTime <= base.requestTime
GROUP BY
base.requestTime
答案 2 :(得分:0)
这是一种通用的方法,提供给定日期的15分钟时段细分:
DECLARE @requests TABLE(requestTime DATETIME, NumberOfSessions INT);
INSERT @requests SELECT '20120605 23:59', 2
UNION ALL SELECT '20120606 00:00', 500
UNION ALL SELECT '20120606 00:07', 400
UNION ALL SELECT '20120606 00:17', 300
UNION ALL SELECT '20120606 23:57', 500
UNION ALL SELECT '20120607 00:00', 100;
DECLARE @day SMALLDATETIME; -- this would be a stored procedure parameter
SET @day = '20120606';
;WITH n AS
(
SELECT TOP 96 n = DATEADD(MINUTE, 15*
(ROW_NUMBER() OVER (ORDER BY [object_id])-1), @day)
FROM sys.all_columns ORDER BY [object_id]
)
SELECT requestTime = n.n, SumNumberOfSessions = COALESCE(SUM(NumberOfSessions), 0)
FROM n LEFT OUTER JOIN @requests AS r
ON r.requestTime >= n
AND r.requestTime < DATEADD(MINUTE, 15, n)
GROUP BY n.n
ORDER BY requestTime;
结果:
requestTime SumNumberOfSessions
----------------------- -------------------
2012-06-06 00:00:00.000 900
2012-06-06 00:15:00.000 300
2012-06-06 00:30:00.000 0
...
2012-06-06 23:30:00.000 0
2012-06-06 23:45:00.000 500