我有这段代码可以按小时计算一组事件的发生次数。现在我需要 MAX COUNT 并在另一个表中输入。我是SQL的新手,我遇到UPDATE语句和MAX以及下面的所有问题。有人可以帮忙吗?谢谢!
SELECT CAST(locate_received_date as date) AS 'ForDate',
DATEPART(hh, locate_received_date) AS 'OnHour',
COUNT (*) AS 'Count'
FROM BELL_DPRA2_locates_fact
WHERE locate_received_date BETWEEN '2016-12-01 00:00:00.000' AND '2016-12-01 23:59:59.999'
GROUP BY CAST(locate_received_date as date), DATEPART(hh, locate_received_date);
编辑:感谢@agfc,这个答案对我有用。我修改了一下为我工作。
UPDATE MyTable
SET MaxHourlyCount =
(SELECT Max(A.HourCount)
FROM (SELECT CAST(locate_received_date as date) AS 'ForDate',
DATEPART(hh, locate_received_date) AS 'OnHour',
COUNT (*) AS HourCount
FROM BELL_DPRA2_locates_fact
WHERE locate_received_date BETWEEN '2016-12-01 00:00:00.000' AND '2016-12-01 23:59:59.999'
GROUP BY CAST(locate_received_date as date), DATEPART(hh, locate_received_date)) AS A)
答案 0 :(得分:0)
-- I'd rename your 'Count' Field to something else not to use the SQL function name.
UPDATE myOtherTable
SET MaxField = SELECT Max(HourCount) FROM (SELECT CAST(locate_received_date as date) AS 'ForDate',
DATEPART(hh, locate_received_date) AS 'OnHour',
COUNT (*) AS HourCount
FROM BELL_DPRA2_locates_fact
WHERE locate_received_date BETWEEN '2016-12-01 00:00:00.000' AND '2016-12-01 23:59:59.999'
GROUP BY CAST(locate_received_date as date), DATEPART(hh, locate_received_date)) As MyMaxResult;
答案 1 :(得分:0)
您可以使用TOP 1
和ORDER BY
返回包含Max HourCount的行。您只需将此作为子查询加入到表中即可更新或将其作为新行插入。如果您包含要移动此数据的表格,我可以更新此答案以反映您的表格。
SELECT TOP 1
CAST(locate_received_date as date) AS 'ForDate',
DATEPART(hh, locate_received_date) AS 'OnHour',
COUNT (*) AS 'Count'
FROM BELL_DPRA2_locates_fact
WHERE
locate_received_date BETWEEN '2016-12-01 00:00:00.000' AND '2016-12-01 23:59:59.999'
GROUP BY
CAST(locate_received_date as date),
DATEPART(hh, locate_received_date)
ORDER BY Count DESC;