我有一个订单表,USER_ID
我ORDER_DATE
想实现这样的目标:
SELECT [USER_ID], [FIRST_ORDER_DATE], [SECOND_ORDER_DATE],
[THIRD_ORDER_DATE], [FOURTH_ORDER_DATE]
FROM ORDERS
我试图创建一个标量函数 ( getFirstOrder
, getSecondOrder
, ...) 但在第三个之后它非常慢
有任何想法吗?
谢谢!
像这样的东西:
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。