您好我正在尝试在SQL中创建一个窗口查询,向我显示自上次订单以来每个客户的日期。
现在向我展示每个订单之间的日子。
在查询中需要更改哪些内容才能显示自每个客户的上一个订单和上一个订单以来的日期?现在它为客户的每个订单显示它。
查询:
SELECT klantnr,besteldatum,
DATEDIFF(DAY,LAG(besteldatum) OVER(PARTITION BY klantnr ORDER BY besteldatum),besteldatum) AS DaysSinceLastOrder
FROM bestelling
GROUP BY klantnr,besteldatum;
答案 0 :(得分:2)
您可以使用row_number()
按besteldatum
为每个klantnr
订购行,并使用派生表(子查询)或common table expression返回最新的两行。
派生表版本:
select klantnr, besteldatum, DaysSinceLastOrder
from (
select klantnr, besteldatum
, DaysSinceLastOrder = datediff(day,lag(besteldatum) over (partition by klantnr order by besteldatum),besteldatum)
, rn = row_number() over (partition by klantnr order by besteldatum desc)
from bestelling
group by klantnr, besteldatum
) t
where rn = 1
;with cte as (
select klantnr, besteldatum
, DaysSinceLastOrder = datediff(day,lag(besteldatum) over (partition by klantnr order by besteldatum),besteldatum)
, rn = row_number() over (partition by klantnr order by besteldatum desc)
from bestelling
group by klantnr, besteldatum
)
select klantnr, besteldatum, DaysSinceLastOrder
from cte
where rn = 1
如果您希望每个客户占一行,rn = 1
是正确的过滤器。如果您想要n
个最新行数,请使用rn <
n + 1。