Тёмный

SQL Tutorial: CASE WHEN with aggregate functions 

DataCamp
Подписаться 166 тыс.
Просмотров 32 тыс.
50% 1

Want to learn more? Take the full course at learn.datacamp.com/courses/in... at your own pace. More than a video, you'll learn hands-on coding & quickly apply skills to your daily work.
---
Great job so far! Let's take a look at CASE statements with aggregate functions.
CASE statements can be used to create columns for categorizing data, and to filter your data in the WHERE clause.
You can also use CASE statements to aggregate data based on the result of a logical test.
Let's say you wanted to prepare a summary table counting the number of home and away games that Liverpool won in each season.
If you've created summary tables in Spreadsheets, you can probably visualize the final table, here --
but how do you get a count of Liverpool's wins in each season?
You guessed it -- a CASE statement. CASE statements are like any other column in your query, so you can include them inside an aggregate function.
Take a look at the CASE statement. The WHEN clause includes a similar logical test to the previous lesson -- did Liverpool play as the home team, AND did the home team score higher than the away team?
The difference begins in your THEN clause. Instead of returning a string of text, you return the column identifying the unique match id. When this CASE statement is inside the COUNT function, it COUNTS every id returned by this CASE statement.
You then add a second CASE statement for the away team, and group the query by the season.
When counting information in a CASE statement, you can return anything you'd like -- a number, a string of text, or any column in the table, SQL is COUNTing the number of rows returned by the CASE statement.
Similarly, you can use the SUM function to calculate a total of any value. Let's say we're interested in the number of home and away goals that Liverpool scored in each season.
This is fairly simple to set up -- if the hometeam_id is Liverpool's, return the home_goal value. The ELSE condition is assumed to be NULL, so the query returns the total home_goals scored by Liverpool in each season.
You can also use the AVG function with CASE in two key ways.
First, you can calculate an average of data. You can do this using CASE in the EXACT same way you used the SUM function. Just change out SUM for AVG in this query, and you instead get the AVG goals Liverpool scored in each season.
You can make the results easier to read using ROUND. ROUND takes 2 arguments -- a numerical value, and the number of decimal points to round the value to.
Place it outside your aggregate CASE statement, and include the number of decimal points at the end.
There, that's much easier to read!
The second key application of CASE with AVG is in the calculation of percentages. This requires a specific structure in order for your calculation to be accurate.
The question we're answering here is, "What percentage of Liverpool's games did they win in each season?"
The first component of this CASE statement is a WHEN clause identifying what you're calculating a percentage of -- in this case, how many games did they win? This is tested in the same way as previous slides, and your THEN clause returns a 1.
The second component identifies Liverpool's games that they LOST, and returns the value 0. All other matches -- ties, games not involving Liverpool -- are excluded as NULLs.
Here are the results of this query ...
... and here's the ROUNDed, more readable version of the results.
Now it's your turn to practice creating CASE statements with aggregate functions.
#SQLTutorial #DataCamp #IntermediateSQL #aggregate #functions

Наука

Опубликовано:

 

9 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 9   
@anon8563
@anon8563 2 года назад
This solved an issue I was struggling with for days. Thank you very much. Oh and the quality of this video is insane. Very clean and "to the point". A lot of effort has put in to this. Thanks again
@paulal0039
@paulal0039 2 года назад
wow! great explanation, you've saved my life!!!!
@scrt1111
@scrt1111 2 года назад
Very best easy demo ...Thanks for sharing take care
@OYeahan
@OYeahan 3 года назад
Why do you use (in 1:28 example) "count" with "then id end" just to calculate the number of rows matching condition? Wouldn't it be more logical to use "sum" and "then 1 else 0 end" (where "else 0" probably can be omitted as NULL counts as 0 I guess)?
@Telugufun427
@Telugufun427 2 года назад
I have written case statement but added columns at the end of the query in group by clause. But records count was increased
@Telugufun427
@Telugufun427 2 года назад
How to group by column 1 with in the case statement
@Telugufun427
@Telugufun427 2 года назад
Could you help me one requirement I have to finish like column 1 has values 10,20, 10,30 etc and column 2 has 1 ,2,3,1,1 and how can we get count of column 1>1 multiply with count of column 2 >1 using case statement. Here 10*1=10 should come as alias column
@algostructure
@algostructure Год назад
Hello and thanks for your effort to be honest your explanation needs an explanation you are just reading the slides, you didn’t mention anything about the mechanism of: COUNT SUM AVG What is the mechanism of the loop and how does it work and count when using aggregate functions with CASE statement. which is significantly important Thanks again
@rhodaime79
@rhodaime79 22 дня назад
This is an intermediate level SQL tutorial, what you’re asking for is introductory. Kindly check earlier videos for that.
Далее
Solving SQL Query | Rows to Column in SQL
1:13:11
Просмотров 161 тыс.
SQL Tutorial - Additive CASE statements
18:41
Просмотров 15 тыс.
SQL Tutorial: Working with temporary tables
5:45
Просмотров 12 тыс.
SQL Window Functions in 10 Minutes
10:13
Просмотров 62 тыс.
SQL CASE Statement | Quick Tips Ep61
10:00
Просмотров 11 тыс.
SQL Tutorial - Nesting CASE statements
8:46
Просмотров 19 тыс.
6 SQL Joins you MUST know! (Animated + Practice)
9:47
Просмотров 115 тыс.
SQL Index |¦| Indexes in SQL |¦| Database Index
9:57
Так ли Хорош Founders Edition RTX 4080 ?
13:00