我需要每小时计数最近N天中表中的申请数量。我正在使用SQL Server2014。类似:
select count(*) from [BankLog].[ProcInst]
where StartDate >= '2019-01-14 09:00:00' and FinishDate <='2019-01-14 10:00:00'
是否有某种方法可以自动获得结果,如:
日期|时间表|计数
答案 0 :(得分:4)
这在黑暗中有点刺痛,但是,实现此目标的一种常用方法是使用理货表格创建所需的所有日期增量。这应该使您走上正确的道路。如果您听不懂,请询问。
USE Sandbox;
GO
DECLARE @StartDate datetime, @EndDate datetime;
SET @StartDate = '20190101';
SET @EndDate = '20190131';
WITH N AS (
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N(N)),
Tally AS(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS I
FROM N N1 --10
CROSS JOIN N N2 --100
CROSS JOIN N N3 --1000
CROSS JOIN N N4 --10000 ≈ 1 Year
CROSS JOIN N N5 --100000 ≈ 11 Years
CROSS JOIN N N6 --1000000 ≈ 110 Years
),
Dates AS(
SELECT DATEADD(HOUR, T.I, @StartDate) AS StartHour,
DATEADD(HOUR, T.I+1, @StartDate) AS EndHour
FROM Tally T
WHERE DATEADD(HOUR, T.I, @StartDate) < DATEADD(DAY, 1, @EndDate))
SELECT CONVERT(date, StartHour) AS [Date],
D.StartHour,
D.EndHour,
COUNT(BLPI.{Column}) AS [Count] --{Column} needs replacing.
FROM Dates D
LEFT JOIN [BankLog].[ProcInst] BLPI ON BLPI.StartDate >= D.StartHour
AND BLPI.StartDate < D.EndHour;
答案 1 :(得分:4)
这可以完成工作
SELECT CAST(StartDate as date) AS TheDate,
DATEPART(hour,StartDate) AS TheHour,
COUNT(*) AS Totals
FROM [BankLog].[ProcInst]
WHERE StartDate >= '2019-01-14 09:00:00' AND FinishDate <='2019-01-14 10:00:00'
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
答案 2 :(得分:3)
您可以尝试使用datepart提取小时并将其分组。
SELECT CONVERT(VARCHAR(10), yourtable.date 111) AS date
,DATEPART(HH,yourtable.date) AS hour
,COUNT(*) AS count
FROM yourtable
WHERE yourtable.date > '2019-01-13 09:00:00'
AND yourtable.date <= '2019-01-14 10:00:00'
GROUP BY
CONVERT(VARCHAR(10), yourtable.date 111)
,DATEPART(HH,yourtable.date)
ORDER BY
DATEPART(HH,yourtable.date)