Thursday 30 September 2010

Query to select last observation by date for each customer

Sometimes you have a table with a list of transactions of each, say, customer and you need the latest picture of each customer. The so called window functions in SQL2003 are instrumental in order to write neat, concise SQL for such purpose.

It would work as follows (in Teradata's SQL dialect):

select
  cust_id,
  status,
  status_date,
row_number() over (partition by cust_id order by status_date desc ) as ranking
from customer_status
qualify ranking = 1;

No comments:

Post a Comment