这是我的SQL Server表:
CREATE TABLE weather (id INT NOT NULL IDENTITY PRIMARY KEY,
place varchar(100) NULL,
description varchar(100) NULL);
地点列包含城市名称。
描述包含天气描述(例如"晴天")。
每个城市每小时插入多个值。现在我想知道什么是" avarage"天气描述,基于我收集的数据。
结果集可能如下所示:
place description
---------------------
london sunny
berlin rainy
以下是我的SQL小提示示例数据:http://sqlfiddle.com/#!6/ee736/2/0
我目前的陈述,尚未完成:
SELECT
w.place, w.description, COUNT(w.description) DESCRIPTION_COUNT
FROM
weather w
GROUP BY
w.place, w.description
此声明未对该地点进行分组,并在说明中找到最大数量。我想这可以通过使用HAVING
和子选择来解决。
答案 0 :(得分:3)
你可以这样做
SELECT top(1) with ties w.place , w.description, COUNT(w.description) DESCRIPTION_COUNT
from weather w
group by w.place, w.description
order by row_number() over (partition by place order by COUNT(w.description) desc);
答案 1 :(得分:1)
我认为你正在寻找"模式" - 最常见的价值:
select w.*
from (select w.city, w.description, count(*) as cnt
row_number() over (partition by city order by count(*) desc) as seqnum
from weather w
group by w.city, w.description
) w
where seqnum = 1;