SQL LAG自上次订单以来的天数

时间:2017-10-09 12:56:35

标签: sql-server tsql lag

您好我正在尝试在SQL中创建一个窗口查询,向我显示自上次订单以来每个客户的日期。

enter image description here

现在向我展示每个订单之间的日子。

在查询中需要更改哪些内容才能显示自每个客户的上一个订单和上一个订单以来的日期?现在它为客户的每个订单显示它。

查询:

SELECT klantnr,besteldatum,
      DATEDIFF(DAY,LAG(besteldatum) OVER(PARTITION BY klantnr ORDER BY besteldatum),besteldatum) AS DaysSinceLastOrder
FROM bestelling
GROUP BY klantnr,besteldatum;

1 个答案:

答案 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

common table expression版本:

;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。