Тёмный

Over clause in SQL Server 

kudvenkat
Подписаться 835 тыс.
Просмотров 241 тыс.
50% 1

over partition by in sql server 2008
sql server over clause partition
partition by clause in sql server 2008
over partition by clause in sql
In this video we will discuss the power and use of Over clause in SQL Server.
Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our RU-vid channel. Hope you can help.
/ @aarvikitchen5572
The OVER clause combined with PARTITION BY is used to break up data into partitions.
Syntax : function (...) OVER (PARTITION BY col1, Col2, ...)
The specified function operates for each partition.
For example :
COUNT(Gender) OVER (PARTITION BY Gender) will partition the data by GENDER i.e there will 2 partitions (Male and Female) and then the COUNT() function is applied over each partition.
Any of the following functions can be used. Please note this is not the complete list.
COUNT(), AVG(), SUM(), MIN(), MAX(), ROW_NUMBER(), RANK(), DENSE_RANK() etc.
Example :
SQl Script to create Employees table
Create Table Employees
(
Id int primary key,
Name nvarchar(50),
Gender nvarchar(10),
Salary int
)
Go
Insert Into Employees Values (1, 'Mark', 'Male', 5000)
Insert Into Employees Values (2, 'John', 'Male', 4500)
Insert Into Employees Values (3, 'Pam', 'Female', 5500)
Insert Into Employees Values (4, 'Sara', 'Female', 4000)
Insert Into Employees Values (5, 'Todd', 'Male', 3500)
Insert Into Employees Values (6, 'Mary', 'Female', 5000)
Insert Into Employees Values (7, 'Ben', 'Male', 6500)
Insert Into Employees Values (8, 'Jodi', 'Female', 7000)
Insert Into Employees Values (9, 'Tom', 'Male', 5500)
Insert Into Employees Values (10, 'Ron', 'Male', 5000)
Go
Write a query to retrieve total count of employees by Gender. Also in the result we want Average, Minimum and Maximum salary by Gender.
This can be very easily achieved using a simple GROUP BY query as show below.
SELECT Gender, COUNT(*) AS GenderTotal, AVG(Salary) AS AvgSal,
MIN(Salary) AS MinSal, MAX(Salary) AS MaxSal
FROM Employees
GROUP BY Gender
What if we want non-aggregated values (like employee Name and Salary) in result set along with aggregated values
You cannot include non-aggregated columns in the GROUP BY query.
SELECT Name, Salary, Gender, COUNT(*) AS GenderTotal, AVG(Salary) AS AvgSal,
MIN(Salary) AS MinSal, MAX(Salary) AS MaxSal
FROM Employees
GROUP BY Gender
The above query will result in the following error : Column 'Employees.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
One way to achieve this is by including the aggregations in a subquery and then JOINING it with the main query as shown in the example below. Look at the amount of T-SQL code we have to write.
SELECT Name, Salary, Employees.Gender, Genders.GenderTotals,
Genders.AvgSal, Genders.MinSal, Genders.MaxSal
FROM Employees
INNER JOIN
(SELECT Gender, COUNT(*) AS GenderTotals,
AVG(Salary) AS AvgSal,
MIN(Salary) AS MinSal, MAX(Salary) AS MaxSal
FROM Employees
GROUP BY Gender) AS Genders
ON Genders.Gender = Employees.Gender
Better way of doing this is by using the OVER clause combined with PARTITION BY
SELECT Name, Salary, Gender,
COUNT(Gender) OVER(PARTITION BY Gender) AS GenderTotals,
AVG(Salary) OVER(PARTITION BY Gender) AS AvgSal,
MIN(Salary) OVER(PARTITION BY Gender) AS MinSal,
MAX(Salary) OVER(PARTITION BY Gender) AS MaxSal
FROM Employees
Text version of the video
csharp-video-tu...
Slides
csharp-video-tu...
All SQL Server Text Articles
csharp-video-tu...
All SQL Server Slides
csharp-video-tu...
All Dot Net and SQL Server Tutorials in English
www.youtube.co...
All Dot Net and SQL Server Tutorials in Arabic
/ kudvenkatarabic

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

 

5 окт 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 110   
@alekseyr7394
@alekseyr7394 8 лет назад
Amazing video, thanks a lot!
@Csharp-video-tutorialsBlogspot
+Алексей Руденко Thank you very much for taking time to give feedback. This means a lot. I am very glad you found the videos useful. I have organised all the Dot Net & SQL Server videos in to playlists, which could be useful to you ru-vid.complaylists?view=1&sort=dd If you need all the videos and slides for offline viewing please visit www.pragimtech.com/kudvenkat_dvd.aspx Slides and Text Version of the videos can be found on my blog csharp-video-tutorials.blogspot.com Tips to effectively use my youtube channel. ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-y780MwhY70s.html If you want to receive email alerts, when new videos are uploaded, please subscribe to my youtube channel. ru-vid.com If you like these videos, please click on the THUMBS UP button below the video. May I ask you for a favor. I want these tutorials to be helpful for as many people as possible. Please share the link with your friends and family who you think would also benefit from them. Good Luck Venkat
@nasarazam
@nasarazam 9 лет назад
Among the best Teachers I have found on RU-vid. He has that skills of shredding complex things and explaining it in a simple manner. Kudos !
@88spaces
@88spaces 3 года назад
What I love about your videos is that you stick to one topic. You don't add material that is not directly related. It makes my life easier. Thank you.
@krzysztofs8535
@krzysztofs8535 7 лет назад
OVER Partintion by RULES. And Venkat Rules ! Tahnk U for educating community. I watched all your videos and i'm impressed. Thank U . Yoy are the best teacher in the world and youtube !
@raqibul1000
@raqibul1000 9 лет назад
The best Teachers and also the best Programmer who have too much clear concept I have found on RU-vid
@Myrslokstok
@Myrslokstok 2 года назад
This actually the way I would like to teach. You show how complicated a solution is and you show and explain a simpler solution, thanks kudos excilent!
@anthonyfranz8317
@anthonyfranz8317 4 года назад
This was an excellent example for the OVER and PARTITION BY clauses. I learned a lot by watching this, again, excellent!!!
@estheticsguru
@estheticsguru Год назад
This was an amazing and easy to understand explanation of over and partition by in relation to aggregate functions!!! Thank you!!!
@onemanenclave
@onemanenclave 5 лет назад
This is the only correct way of explaining OVER: by relating it with GROUP BY.
@kimbowayasin6940
@kimbowayasin6940 3 года назад
You have really simplified my work in SQL queries, thank you sir
@umut2243
@umut2243 4 года назад
I really understood. Before, I always stucked with this problem: whenever I want to retrieve columns like names, salary etc. as grouping with another column that error comes up. However, if we use subquery we'll able to fix that. But subquery may be fuzzy so that we use over. It's brillant, I'm really happy to understand this.
@VersinKettorix
@VersinKettorix 8 лет назад
Thank you for taking the time to post this video. Your explanation of this function was the best I have seen when trying to figure out the use of the "Partition.. Over()" function. Very helpful.
@mudasir989
@mudasir989 4 года назад
You are ray of light for lot of people Venkat. … God bless you !!!!!
@Csharp-video-tutorialsBlogspot
@Csharp-video-tutorialsBlogspot 4 года назад
Hello Mudasir - Thank you very much Greatly honoured. Means a lot. I have included all the SQL tutorial videos, slides and text articles in sequence on the following page. Hope you will find it handy. www.pragimtech.com/courses/sql-server-tutorial-for-beginners/ If you have time, can you please leave your rating and valuable feedback on the reviews tab. It really helps us. Thank you. Good luck and all the very best with everything you are doing.
@MatthewPimenta
@MatthewPimenta 3 года назад
Thank you for this video! Clean, clear, and I really appreciate the comparisons to other methods.
@allangao4783
@allangao4783 4 года назад
You are a great teacher. Very good examples, very helpful tutorials, and your English is really good so it is easy to follow along to your instruction!
@libertymudzingwa1206
@libertymudzingwa1206 4 года назад
This is amazing!!! You are very good at explaining complex concepts and make them easy to understand
@carmenliu3765
@carmenliu3765 7 лет назад
Thanks for the video and making it easy to understand!
@prasadrsby5274
@prasadrsby5274 8 лет назад
Dear sir it s very nice and i am watching ur videos up to 68 part i learning every day new concepts
@aashishmalhotra
@aashishmalhotra 2 года назад
Kudos very well explained sir good example taken. Please bring a SQL interview series. Nowadays it well appreciated by audience.
@edwinmchaffie5091
@edwinmchaffie5091 5 лет назад
Venkat, You should have a lot more subscribers.. Your vids are tops!!
@brindhaganesan3580
@brindhaganesan3580 6 лет назад
This is an excellent channel. I am so glad I found it!
@saurabhdsawant
@saurabhdsawant 5 лет назад
Thanks @kudvenkat for such clean explanation! I was confused about use of over for long time and I struck the gold here
@stevenaleman7454
@stevenaleman7454 Год назад
thank you for sharing this knowledge...it really helped me today. ✌
@slavaseagull7349
@slavaseagull7349 8 лет назад
Thank you! It is a very helpfull video tutorial. Now the Over clause is realy clear for me.
@ALLCAPS
@ALLCAPS 3 года назад
what a powerful tool! -over.
@ni12907
@ni12907 3 года назад
Very good explanation, superrrrr !!! thanks 💕
@mickeysaini
@mickeysaini 3 года назад
Very Well explained Alternate Solution using CTE select Gender,count(Gender) GenderTotal,avg(Salary) AvgSalary, Min(Salary) as MIN , Max(Salary) as MaxSalary from (select Salary,Gender,Count(Gender) over (partition by Gender) as RN from Employees ) result group by Gender
@MrCardeso
@MrCardeso 9 лет назад
Very nice! Another useful tool! Thanks.
@davidvo30
@davidvo30 7 лет назад
Excellent tutorial video with practical samples, thank you.
@Frickenchies
@Frickenchies 7 лет назад
Very well explained, thank you!
@leonidasparigoris1389
@leonidasparigoris1389 3 года назад
You're a great teacher. Thanks
@petetalbert
@petetalbert 7 лет назад
Such clear explanation, thank you!
@raptorslam84
@raptorslam84 4 года назад
Genus on the way you explained this !! Thank you !!
@TheThodi
@TheThodi 7 лет назад
easily understandable, great job!
@Freeman1125
@Freeman1125 6 лет назад
Excellent video,clear logic ! thanks a million man
@idhamhafidz
@idhamhafidz 6 лет назад
Thank you so much. You are an awesome teacher
@303TheAlex
@303TheAlex 8 лет назад
Thank you for these tutorials, they are really great.
@QuickZ_
@QuickZ_ 3 года назад
Excellent teaching as always!
@sudhanshuranjan632
@sudhanshuranjan632 2 года назад
To the point this is good stuff👌👍
@srinivasreddypachika8716
@srinivasreddypachika8716 2 года назад
Awesome Explanation!
@shailjamishra9423
@shailjamishra9423 2 года назад
Thank you very very much!!!🙏🙏
@bajanguy2664
@bajanguy2664 4 года назад
Very well explained! New subscriber inserted to the table.
@juanpablo-kw6th
@juanpablo-kw6th 8 лет назад
this mean a lot for me thanks for teaching the world
@ateeqhalikhan4012
@ateeqhalikhan4012 2 месяца назад
Superb explanation thanks alot
@UnstoppableBird
@UnstoppableBird 4 года назад
This is very clear, thank you so much!
@choudharymustansar3749
@choudharymustansar3749 5 лет назад
Easy and comprehensive Thanks
@DaveClarkFive
@DaveClarkFive 6 лет назад
Great explanation and examples.
@ricardovalle8360
@ricardovalle8360 6 лет назад
Great Video, pretty clear and didactic.
@AliHassanLearnMVC
@AliHassanLearnMVC 9 лет назад
very nice...thank u so much...
@swathibandarupalli803
@swathibandarupalli803 2 года назад
Hello Venkat, In this example, in over clause, we are not specifying rows between clause. How its summing up all the rows values. Ideally it should take unbounded preceeding and current row as default. Can you please explain
@ritiktripathi8947
@ritiktripathi8947 Год назад
The default window frame without the ORDER BY is the whole partition. But when you use the ORDER BY, the default window frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
@RaviShankar-jm1qw
@RaviShankar-jm1qw 8 лет назад
Awesome video. So nicely explained!!!!
@ReinaldoHernandezOchoa
@ReinaldoHernandezOchoa 3 года назад
great video, thanks!
@ladhkay
@ladhkay 5 лет назад
Nicely explained!
@xuanquangnguyen2291
@xuanquangnguyen2291 4 года назад
Thank you, the video is so useful!!!
@mahipalkamanchi
@mahipalkamanchi 9 лет назад
AWESOME ....! THANK U SIR...!
@shrikanthsingh8243
@shrikanthsingh8243 3 года назад
simply awesome
@subtlehustle6300
@subtlehustle6300 2 года назад
Well explained 👍
@marshalljackson1385
@marshalljackson1385 6 лет назад
Well explained video. Thank you.
@tannubajpai4782
@tannubajpai4782 3 года назад
thnx u for ur services
@YenNguyen-nf9uv
@YenNguyen-nf9uv 3 года назад
Amazing tutorial. Thank you
@Csharp-video-tutorialsBlogspot
@Csharp-video-tutorialsBlogspot 3 года назад
Thank you Yen. Means a lot. Your review and feedback really helps. Hope you have a few minutes to write a review. Thank you for your time. g.page/r/CdKOVS3cTnYnEAg/review
@amanansari5567
@amanansari5567 6 лет назад
Thank you so much it was great help
@asitkumarmohanty2579
@asitkumarmohanty2579 7 лет назад
superbly done. Kudos.. :)
@spyrex3988
@spyrex3988 Год назад
this is so amazing stuff
@aliazad1118
@aliazad1118 5 лет назад
As usual perfect
@izulien
@izulien 3 года назад
Super neat concept! Is there a large performance difference between sub query vs over method?
@עדיפרי-כ2ז
@עדיפרי-כ2ז 7 лет назад
Thanks you! very useful!
@heathermari83
@heathermari83 6 лет назад
Thank you very much!!!
@muhammadrehbarsheikh8498
@muhammadrehbarsheikh8498 9 лет назад
Thank you sir!!
@calvinharris4771
@calvinharris4771 2 месяца назад
Thank you 💌
@bhaskardot
@bhaskardot 2 года назад
thankyou very much
@timhxf1
@timhxf1 7 лет назад
why this is no ROWS clause in OVER() but the AVG() calculates for all rows in the partition?
@luizfabrette7450
@luizfabrette7450 7 лет назад
Well explained! Thanks
@AjayChorat
@AjayChorat 8 лет назад
Thank you Venkat.. :)
@davidgreenfeld9691
@davidgreenfeld9691 6 лет назад
Great!
@funkychimp
@funkychimp 6 лет назад
Hi Venkat. Thank you for your tutorials. Can I ask. I thought the OVER clause had to be used with the ORDER BY clause. I'm just wondering here why the default 'RANGE BY UNBOUNDED PRECEEDING AND UNBOUNDED CURRENT ROW' does not apply here. Is it because you have used the PARTITION BY clause without the ORDER BY clause? Thanks funkychimp
@shubamsalaria971
@shubamsalaria971 Год назад
same question....does anyone has it's answer
@vikasmatrupally
@vikasmatrupally 7 лет назад
Thanks for the amazing n interesting videos. Helps a lot in our daily tasks. I am not sure the discussion forum is active. Could you please explain how to extract only the Max. Salaries for Male and Female along with other column fields for that record. Thanks !
@dosovi4548bustayes
@dosovi4548bustayes 9 лет назад
thank you merlin :-D
@SanjaySony303
@SanjaySony303 9 лет назад
hi sir .good afternoon thank you for providing video tutorial of .net sir would you teach, about data View and its uses and properties And DataTable
@cd1168
@cd1168 6 лет назад
excellent
@TheEverydayAnalyst
@TheEverydayAnalyst Год назад
We are partitioning 4 times in this example. Which query would be an optimal one in terms of performance?
@johncross116
@johncross116 8 лет назад
THANK YOU!
@ivankevamo
@ivankevamo 8 лет назад
Thanks mate!
@kamalpatwa123
@kamalpatwa123 7 лет назад
Thank You
@RyanHeaney42
@RyanHeaney42 6 лет назад
Thanks! This helped!
@ashishrao5635
@ashishrao5635 9 лет назад
Hi, Could you please also explain how to us Red Gate s/w for transferring data from one server to another
@temprmj1
@temprmj1 6 лет назад
Forgive my ignorance but wouldn't the query in the JOIN clause be a Derived table and not a sub query?
@shubamsalaria971
@shubamsalaria971 Год назад
why didn't you use "unbounded preceding and unbounded following" here as u used in other video?.....could u please explain it
@yurifontoura2189
@yurifontoura2189 8 лет назад
Indian, Always amazing! What would about us, without them?!
@jmjohnson42342
@jmjohnson42342 8 лет назад
+Yuri Fontoura What would about us, indeed.
@malharjajoo7393
@malharjajoo7393 8 лет назад
+Yuri Fontoura _ at least he is explaining difficult concepts man pardon his english
@yurifontoura2189
@yurifontoura2189 8 лет назад
+malhar jajoo I'm not criticizing him, in any way. Quite opposite of that. I just noticed the Indians are in everywhere seeding great materials. As SQLAuthority and JavaBrains channel have done as well.
@bahadirezici
@bahadirezici 5 лет назад
Yu da best!!!
@javidhesenov7611
@javidhesenov7611 2 года назад
thanks
@f1r3shoot
@f1r3shoot 8 лет назад
My respect
@anweshgandham6776
@anweshgandham6776 3 года назад
Does over function don't take default range as unbounded preceding and current row ??
@jayjayf9699
@jayjayf9699 6 лет назад
How come the avg in the over clause is not generating running average, I am confused what generates a running aggregate or just one value per partition by
@richardlew3667
@richardlew3667 3 года назад
On page 6 of the slide, how come Gender is in the subquery when it doesn't have aggregations?
@excaliber4ps
@excaliber4ps 3 года назад
👍
@santhoshb4545
@santhoshb4545 3 года назад
At 6:22 in over clause used table, how do you get Name column Tom Ron Ben Todd Mark John in this sorting. Can someone xplain please, Thanks in advance
@kevinberg7212
@kevinberg7212 2 года назад
The number of views for videos such as these makes me worry for our future. This video should have 2M views by now.... oh wait, let's go watch baby shark one more time
@codyhayes5926
@codyhayes5926 5 лет назад
I love you
@fathallahilyes529
@fathallahilyes529 4 года назад
WHAT DO OVER(*) ?
@sarojsahoo8763
@sarojsahoo8763 2 года назад
SELECT COUNT(GENDER) AS GENDER_TOTAL,GENDER,NAME,SALARY,AVG(SALARY) AS AVG_SAL, MIN(SALARY) AS MIN_SAL, MAX(SALARY) AS MAX_SAL FROM EMPLOYEES GROUP BY GENDER; -- thIs works in MYSQL dont know how
Далее
Row Number function in SQL Server
7:24
Просмотров 240 тыс.
Women’s Celebrations + Men’s 😮‍💨
00:20
Mcdonalds cups and ball trick 🤯🥤 #shorts
00:25
Просмотров 484 тыс.
Rank and Dense Rank in SQL Server
10:08
Просмотров 240 тыс.
Learn GROUP BY vs PARTITION BY in SQL
14:03
Просмотров 37 тыс.
Window functions in SQL Server
11:00
Просмотров 220 тыс.
SQL Ranking Functions: Part 1 The Over Clause
8:51
Просмотров 31 тыс.
NTILE function in SQL Server
5:10
Просмотров 95 тыс.
GROUPING ID function in SQL Server
12:37
Просмотров 60 тыс.
Women’s Celebrations + Men’s 😮‍💨
00:20