SQL 服务器分组按每小时的日期时间计数和更新最大值计数为 table?

SQL Server Group by Count of DateTime Per Hour and Update Max count into table?

我有这段代码可以每小时计算一组事件的发生次数。现在我需要 MAX COUNT 并将其输入另一个 table。我是 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)
-- 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; 

您可以使用 TOP 1ORDER BY 到 return 具有 Max HourCount 的行。您只需将此作为子查询加入 table 即可更新或将其作为新行插入。如果您包括要将此数据移动到的 table,我可以更新此答案以反映您的 table。

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;