我怎样才能给日期排名?

时间:2012-09-19 09:10:05

标签: sql ranking rank

我有一张包含USER_IDORDER_DATE的订单表 我想实现这样的事情:

SELECT [USER_ID], [FIRST_ORDER_DATE], [SECOND_ORDER_DATE], 
       [THIRD_ORDER_DATE], [FOURTH_ORDER_DATE]
FROM ORDERS 

我尝试创建标量函数(getFirstOrdergetSecondOrder,...) 但在第三次之后非常缓慢

任何想法?

谢谢!

1 个答案:

答案 0 :(得分:3)

这样的事情:

select user_id, 
       max(case when rnk = 1 then date_col else null end) as first_order_date,
       max(case when rnk = 2 then date_col else null end) as second_order_date,
       max(case when rnk = 3 then date_col else null end) as third_order_date
from (
     select user_id, 
            date_col,
            dense_rank() over (partition by user_id order by date_col) as rnk
     from orders
) t
group by user_id;

您没有指定DBMS。以上是适用于大多数现代DBMS的ANSI SQL。