计算 SQL Server 中值随时间变化的模式(或频率)分布
给定下表,如何计算每小时模式,或每小时频率最高的值?
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)
然而,这会产生每小时每个不同值的频率。 如何添加约束以仅返回每小时最大频率的值?
谢谢
Given the following table, how does one calculate the hourly mode, or value with the highest frequency by hour?
CREATE TABLE Values
(
ValueID int NOT NULL,
Value int NOT NULL,
LogTime datetime NOT NULL
)
So far, I've come up with the following query.
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)
However, this yields the frequency of each distinct value by hour. How do I add a constraint to only return the value with the maximum frequency by hour?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面的查询可能看起来很奇怪......但它有效并且它给了你你想要的。 此查询将为您提供特定“小时”(时间片)内出现频率最高的值。
我不划分为年、月、日等...仅按小时(按照您的要求),即使您的示例查询中有其他字段。
我选择在下面执行“MAX(值)”,因为可能会出现多个“值”并列第一的情况,并且每小时频率最高。 如果您愿意,您可以选择进行 MIN、MAX 或其他“决胜局”。
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.
嵌套聚合...
Nest the aggregates...