1

This is my SQL Server table:

CREATE TABLE weather (id INT NOT NULL IDENTITY PRIMARY KEY,
                      place varchar(100) NULL,
                      description varchar(100) NULL);

The place column contains a city name.

The description contains the weather description (e.g. "sunny").

Multiple values are inserted per hour per city. Now I want to know what is the "avarage" weather description, based on my collected data.

A result set could look like this:

place     description
---------------------
london    sunny
berlin    rainy

Here is my SQL fiddle with sample data: http://sqlfiddle.com/#!6/ee736/2/0

My current statement, which is not completed yet:

SELECT 
    w.place, w.description, COUNT(w.description) DESCRIPTION_COUNT
FROM
    weather w 
GROUP BY 
    w.place, w.description

This statement misses to group the place and find the maximum count on the description. I guess it can be solved by using HAVING and subselects.

3
  • Do you wish to retrieve the data for records which have maximum occurance of description for each city Commented Jul 11, 2017 at 12:54
  • @Kapil Exactly, that's what I need. For my SQL fiddle it should be "Boston|mostly cloudy" and second row "London|sunny" Commented Jul 11, 2017 at 12:55
  • dev.mysql.com/doc/refman/5.7/en/… Commented Jul 11, 2017 at 13:00

2 Answers 2

3

You can do it this way

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain the extraordinary things like top(1) with ties or order by row_number() over (partition..?
learn.microsoft.com/en-us/sql/t-sql/functions/… Plus, MS Sql allows row_number() in ORDER BY clause of SELECT statement
1

I think you are looking for the "mode" -- the most common value:

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;

1 Comment

Gordon: I just tried to correct your answer to let it works (as I think it was correct as main idea). Obviously feel free to delete, edit, or anything you want to do with my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.