Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Site Related Forums
 Article Discussion
 Article: SQL Sever 2005: Using OVER() with Aggregate Functions

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2007-05-21 : 09:57:06
One of new features in SQL 2005 that I haven't seen much talk about is that you can now add aggregate functions to any SELECT (even without a GROUP BY clause) by specifying an OVER() partition for each function. Unfortunately, it isn't especially powerful, and you can't do running totals with it, but it does help you make your code a little shorter and in many cases it might be just what you need.

Article Link.

Scott Pletcher
Starting Member

2 Posts

Posted - 2007-06-20 : 11:33:37
Very helpful info, and well presented.
Go to Top of Page

addytude
Starting Member

12 Posts

Posted - 2008-02-17 : 13:09:27
most informative! Thanks
Go to Top of Page

eldkir
Starting Member

1 Post

Posted - 2008-03-13 : 12:11:11
Great Information!!

I have a question that may be applicable to this function. I am trying to do a count of the number of times customers have purchased from us. For example, I need these 3 buckets; Once, Twice and 3 or more. Would I incorporate the Over function here, or is there something else I should be using? Thanks in advance for your help!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-03-23 : 20:18:24
quote:
Originally posted by eldkir

Great Information!!

I have a question that may be applicable to this function. I am trying to do a count of the number of times customers have purchased from us. For example, I need these 3 buckets; Once, Twice and 3 or more. Would I incorporate the Over function here, or is there something else I should be using? Thanks in advance for your help!


You can use OVER in this scenario as follows:-
SELECT tmp.Category,Count(tmp.customer_id)
FROM
(
SELECT t.customer_id,
CASE
WHEN t.CustSum =1 THEN 'Once'
WHEN t.CustSum=2 THEN 'Twice'
ELSE '3 or more'
END AS Category
FROM
(
SELECT DISTINCT c.customer_id,
SUM(p.purchase_id) OVER (PARTITON BY c.customer_id) AS CustSum
FROM Customer c
INNER JOIN Purchase p
ON p.customer_id=c.customer_id
)t
)tmp
GROUP BY tmp.Category

Go to Top of Page
   

- Advertisement -