首页 > 解决方案 > SQL Server 2008。仅当先前不同时才重复顺序

问题描述

假设我有这张桌子:

Price   | OrderDate   | OrderID
--------+-------------+-----
5.50000 | 2017-11-02  | 77319 
5.30000 | 2017-11-02  | 77320
5.50000 | 2017-11-09  | 77463
5.50000 | 2017-11-16  | 77633
5.50000 | 2017-11-23  | 77839
5.25000 | 2017-11-23  | 77840
5.35000 | 2017-11-30  | 78012
5.50000 | 2017-12-07  | 78138
5.50000 | 2017-12-14  | 78283

我需要得到这个结果

Price   | OrderDate   | OrderID
--------+-------------+--------
5.50000  2017-11-02     77319 
5.30000  2017-11-02     77320
5.50000  2017-11-09     77463
5.25000  2017-11-23     77840
5.35000  2017-11-30     78012
5.50000  2017-12-07     78138

粗体的值,我需要分组并且只得到 1 行。表格的顺序应该和结果一样。

我不知道如何做到这一点。

有任何想法吗?

谢谢!

标签: sqlsql-serversql-server-2008

解决方案


假设您可以使用lag()

with data as (
    select *, lag(Price) over (order by OrderId) as lastPrice
    from T
)
select *
from data
where coalesce(Price, -1) <> lastPrice;

否则,假设您可以使用cross apply

select t.*
from T t cross apply (
    select max(OrderId) priorOrderId from T t2 where t2.OrderId < t.OrderId
) left outer join T t3 on t3.OrderId = t2.priorOrderId
where coalesce(t3.Price, -1) <> t.Price;

否则仍然可以重写:

with data as (
    select *, (select max(OrderID from T t2 where t2.OrderId < t.OrderId) as priorOrderId
    from T t
)
select d.*
from data d left outer join T t on t.OrderId = d.priorOrderId
where coalesce(t.Price, -1) <> d.Price;

推荐阅读