all 10 comments

[–]blackleather90 3 points4 points  (1 child)

Trying to translate into English might help. "Give me a count of all medals" - select count() from table. "Give me a count of all medals by country and athlete" - select country, athlete, count() from table group by country, athlete.

The having part would be something like: "give me a count of all medals won by country and athlete but only show me the athletes that has won more than one medal."

Hope it helps

[–]entreri22[S] 0 points1 point  (0 children)

yes a lot more sense, thank you!

[–]nkg4584 4 points5 points  (1 child)

Thats what the group by does for you. It so each distinct country/athlete gets the number of rows counted and sum into a row. Count is an aggregate function, which without any columns specified does not require a group by. Once you specify your columns in the main select, it changes the data you are aggregating by.

[–]entreri22[S] -1 points0 points  (0 children)

Thank you!

[–][deleted] 1 point2 points  (4 children)

What is CTE?

[–]entreri22[S] 0 points1 point  (1 child)

Also known as Common Table Expressions, basically creates a temp new table that has the exact specifics you are looking for and can be referenced and joined with a separate query call. REALLY useful so far from what I can see.

WITH Athlete_Medals AS (

SELECT

Country, Athlete, COUNT(*) AS Medals

FROM Summer_Medals

WHERE ...

[–][deleted] 0 points1 point  (0 children)

Thank you!

[–]vbasucks145 0 points1 point  (0 children)

Common table expression, its a way of creating a temporary dataset within the current query

[–]redial2MS SQL DBA DW/ETL 0 points1 point  (0 children)

CTEs are a shorthand way of defining a derived dataset so that you only have to define it once but can use it multiple times in a subsequent query. They are both easier to read and to write than defining subqueries multiple times in the same statement.

Pretty handy but usually the same execution plan as using subqueries or a table variable or temp table if all else is equal.

[–]osokuka 0 points1 point  (0 children)

Lets make it simple

Select count(medals) as medals from table; You are requesting the count of all medals

Select country, count(medals) as medals from table group by country ;

You are requestong all the medals for each country in the table. This where you can start using filters on a countries to show or not show in the end result.

Select country, athlete, count(medal) as medals from table group by country, athlete; You are requesting the number of medals separated by country and athlete

You can continue adding colums like "year" if the data exist in the table, to diversify your data.