我有一张包含USER_ID
和ORDER_DATE
的订单表
我想实现这样的事情:
SELECT [USER_ID], [FIRST_ORDER_DATE], [SECOND_ORDER_DATE],
[THIRD_ORDER_DATE], [FOURTH_ORDER_DATE]
FROM ORDERS
我尝试创建标量函数(getFirstOrder
,getSecondOrder
,...)
但在第三次之后非常缓慢
任何想法?
谢谢!
答案 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。