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
 General SQL Server Forums
 New to SQL Server Programming
 How to take the first from each customer

Author  Topic 

amarundo
Starting Member

9 Posts

Posted - 2012-01-04 : 17:13:18
Hi,

I have a TABLE (really it's the result of a select statement) that has something like this:
Customer ID, Order Amount, Order Date
and may have multiple entries per customer.

I'm interested in SELECTing the first occurrence of each Customer Id, and ignoring the rest.

How do I do that?

Thanks.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-04 : 17:20:50
How do you define first? For example, if you want the row with the earliest Order Date then you could do this:

select
CustomerID,
OrderAmount,
OrderDate
from
(
select
CustomerID,
OrderAmount,
OrderDate,
row_number() over (partition by CustomerID order by OrderDate) as RN
from
YourTable
) s
where
RN = 1;
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2012-01-04 : 17:27:22
I gotta do a perf test

Is that really better than WHERE EXISTS?



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-04 : 19:58:51
quote:
Originally posted by X002548

I gotta do a perf test

Is that really better than WHERE EXISTS?

Brett


Do you mean "where exists" against a subquery where you pick the min value (or using some other method)? Or something else?
Go to Top of Page
   

- Advertisement -