Click here to Skip to main content
14,977,910 members
Articles / Database Development
Tip/Trick
Posted 2 May 2011

Stats

12.7K views
1 bookmarked

T-sql over clause to aggregating without groupby

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
2 May 2011CPOL
A nice way to get aggregated value without group by
Whenever we are to aggregate something, we group the query on the field on which we want the aggregation.
Consider the condition suppose we have to show sales of all items with the sum of their group - we have four Item groups Food, beverage, cosmetics and others and our sale is like this:


Item	Group	  Sales
---------------------------------

Item1	Food	   100
Item2	Beverage   250
Item3	Food	   200
Item4	Food	   300
Item5	Others	   500
Item6	Beverage   100
Item7	Cosmetics 1000
Item8	Cosmetics 1000
Item9	Others	   500
Item10	Food	   300
Item11	Others	   700

----------------------------------


and we want the result as:


Item	Group	 Sales	   Total Group Sale
----------------------------------------------------
Item1	Food	   100	    900
Item2	Beverage   250	    350
Item3	Food	   200	    900
Item4	Food	   300	    900
Item5	Others	   500	   1700
Item6	Beverage   100	    350
Item7	Cosmetics 1000	   2000
Item8	Cosmetics 1000	   2000
Item9	Others	   500	   1700
Item10	Food	   300	    900
Item11	Others	   700	   1700
-----------------------------------


We can achieve this by using over clause-
First create the table-
SQL
Create table #temp ( Item  Varchar(200), Group varchar(200), sales INT)
--Insert values
INSERT INTO #TEMP
select Item1,Food,100 union all
select Item2,Beverage,250 union all
select Item3,Food,200 union all
select Item4,Food,300 union all
select Item5,Others,500 union all
select Item6,Beverage,100 union all
select Item7,Cosmetics,1000 union all
select Item8,Cosmetics,1000 union all
select Item9,Others,500 union all
select Item10,Food,300 union all
select Item11,Others,700 

Now to get the desired result we can write the query as-
SQL
Select Item, Group, Sales, sum(Sales) OVER (Partition by Group) as 'Total Group Sale' from #temp


means we can aggregate the values without group by and the syntax for this is very simple.

SQL
select <your column list> ,<aggregating function>(<col to aggregate>) over (partition by <column list to group>)


Hope this will help you sometime.

--Pankaj

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

pankajupadhyay29
Architect
India India
• An Architect, developer, trainer, and student
• 10 years of experience in Architecture and Development of enterprise applications
• Extensive knowledge in designing and developing Web-based enterprise applications using open source and Microsoft Technologies
• Extensive experience in Angular, AngularJS, ReactJs, NodeJs, JavaScript, ASP.Net, C#, CSS, HTML

Comments and Discussions

 
-- There are no messages in this forum --