1

给定下表,如何计算每小时模式或每小时频率最高的值?

CREATE TABLE Values
(
    ValueID int NOT NULL,
    Value int NOT NULL,
    LogTime datetime NOT NULL
)

到目前为止,我已经提出了以下查询。

SELECT count(*) AS Frequency, 
DatePart(yy, LogTime) as [Year], 
DatePart(mm, LogTime) as [Month],
DatePart(dd, LogTime) as [Day], 
DatePart(hh, LogTime) as [Hour]
FROM Values
GROUP BY 
Value,
DatePart(yy, LogTime), 
DatePart(mm, LogTime),
DatePart(dd, LogTime), 
DatePart(hh, LogTime)

但是,这会按小时产生每个不同值的频率。如何添加约束以仅按小时返回具有最大频率的值?

谢谢

4

2 回答 2

2

The following query may look odd... but it works and it gives you what you want. This query will give you the value that had the highest frequency in a particular "hour" (slice of time).

I am NOT dividing into Year, Month, Day, etc... only hour (as you requested) even though you had those other fields in your example query.

I chose to do "MAX(Value)" below, because the case can come up where more than one "value" tied for first place with the highest frequency by hour. You can choose to do MIN, or MAX or some other 'tiebreaker' if you want.

WITH GroupedValues (Value, Frequency, Hour) AS
    (SELECT
        Value,
        COUNT(*) AS Frequency,
        DATEPART(hh, LogTime) AS Hour
    FROM
        dbo.MyValues
    GROUP BY
        Value,
        DATEPART(hh, LogTime))

SELECT
    MAX(Value) AS Value,
    a.Hour
FROM
    GroupedValues a INNER JOIN
        (SELECT MAX(Frequency) AS MaxFrequency,
            Hour FROM GroupedValues GROUP BY Hour) b
    ON a.Frequency = b.MaxFrequency AND a.Hour = b.Hour
GROUP BY
    a.Hour
于 2008-11-02T20:22:03.127 回答
1

嵌套聚合...

SELECT
    MAX(Frequency) AS [Mode],
    [Year],[Month],[Day],[Hour]
FROM
    (SELECT
         COUNT(*) AS Frequency, 
         DatePart(yy, LogTime) as [Year], 
         DatePart(mm, LogTime) as [Month], 
         DatePart(dd, LogTime) as [Day], 
         DatePart(hh, LogTime) as [Hour]
    FROM 
         Values 
    GROUP BY 
         Value, 
         DatePart(yy, LogTime), 
         DatePart(mm, LogTime), 
         DatePart(dd, LogTime), 
         DatePart(hh, LogTime)
    ) foo
GROUP By
    [Year],[Month],[Day],[Hour]
于 2008-11-02T18:34:11.380 回答