Tuesday, February 21, 2012

retrieve first record of each customer

I have to retrieve first and last record of each customer according to the Date. Each customer has 10 - 15 records in the table and there are 3000 customers.
how can I retrieve this data.

regardsYou should do something like this:

select *
from table_name a
join (select customer_id, max(date) max_date, min(date) min_date
from table_name
group by custormer_id) b on a.customer_id = b.customer_id and
(date = max_date or date = min_date )

Good Luck.|||Unless you need field information from both records on the one line then you could use:

SELECT
customers.customerid
(SELECT Top 1 c1.DetailsID FROM customerdetails c1 ORDER BY c1.CreateDate ASC) DetailsIDFirst,
(SELECT Top 1 c1.DetailsID FROM customerdetails c1 ORDER BY c1.CreateDate DESC) DetailsIDLast
FROM customers

I'm bringing back the DetailsID - but you could recall any field using this.

Hope this helps.

No comments:

Post a Comment