我有以下查询,试图在每天的小时中获取平均计数。我得到的总数没有问题,但是我似乎无法获得平均值。
任何人都可以看到我在以下查询中出现的问题以及如何以以下格式获取结果吗?
SELECT
[Day],
[Hour],
[DayN],
Totals,
AVG(Totals) AS [Avg]
FROM
(
SELECT
[Day] = DATENAME(WEEKDAY, StartDate),
[DayN] = DATEPART(WEEKDAY, StartDate),
[Hour] = DATEPART(HOUR,StartDate),
Totals = COUNT(*)
from
Visit
where
StartDate >= '01 Jan 2019'
GROUP BY
DATENAME(WEEKDAY,StartDate),
DATEPART(WEEKDAY,StartDate),
DATEPART(HOUR,StartDate)
) AS q
GROUP BY [Day], [Hour], Totals, [DayN]
ORDER BY DayN;
样本数据:(更多信息https://justpaste.it/65w8z)
CREATE TABLE [dbo].[Visit](
[VisitID] [int] NOT NULL,
[StartDate] [datetime] NULL
)
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30513, CAST(N'2019-01-01T00:06:28.480' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30514, CAST(N'2019-01-01T00:07:23.637' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30515, CAST(N'2019-01-01T00:14:44.840' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30516, CAST(N'2019-01-01T00:16:05.030' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30517, CAST(N'2019-01-01T00:18:23.787' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30518, CAST(N'2019-01-01T00:20:33.073' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30519, CAST(N'2019-01-01T00:20:42.450' AS DateTime))
GO
INSERT [dbo].[Visit] ([VisitID], [StartDate]) VALUES (30520, CAST(N'2019-01-01T00:25:03.303' AS DateTime))
GO
答案 0 :(得分:1)
尝试此操作,您需要单独获取平均值,请运行
SELECT [Day], [Hour], [DayN], Totals, (
SELECT avg(totals)
FROM
( SELECT [Day] = DATENAME(WEEKDAY, StartDate),
[DayN] = DATEPART(WEEKDAY, StartDate),
[Hour] = DATEPART(HOUR,StartDate),
Totals = COUNT(*)
FROM Visit
WHERE StartDate >= '01 Jan 2019'
GROUP BY DATENAME(WEEKDAY,StartDate),
DATEPART(WEEKDAY,StartDate),
DATEPART(HOUR,StartDate) ) AS qq
WHERE q.[day]=qq.[day]) [Avg]
FROM
( SELECT [Day] = DATENAME(WEEKDAY, StartDate),
[DayN] = DATEPART(WEEKDAY, StartDate),
[Hour] = DATEPART(HOUR,StartDate),
Totals = COUNT(*)
FROM Visit
WHERE StartDate >= '01 Jan 2019'
GROUP BY DATENAME(WEEKDAY,StartDate),
DATEPART(WEEKDAY,StartDate),
DATEPART(HOUR,StartDate) ) AS q
ORDER BY DayN;
答案 1 :(得分:0)
尝试:
1 1.0
2 17.4
3 0.0
4 7.0
5 2.3
6 0.0
7 4.4
您是否需要SELECT
[Day],
[Hour],
[DayN],
Totals,
AVG(Totals) AS [Avg],
A
FROM
(
SELECT
[Day] = DATENAME(WEEKDAY, StartDate),
[DayN] = DATEPART(WEEKDAY, StartDate),
[Hour] = DATEPART(HOUR,StartDate),
Totals = COUNT(*),
COUNT(1)/Count(distinct DATEPART(HOUR, StartDate)) A
from
Visit
where
StartDate >= '01 Jan 2019'
GROUP BY
DATENAME(WEEKDAY,StartDate),
DATEPART(WEEKDAY,StartDate),
DATEPART(HOUR,StartDate)
) AS q
GROUP BY [Day], [Hour], Totals, [DayN],A
ORDER BY DayN;
?如果不这样做,则可以删除最后2行