sql - 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 行。表格的顺序应该和结果一样。
我不知道如何做到这一点。
有任何想法吗?
谢谢!
解决方案
假设您可以使用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;
推荐阅读
- intellij-idea - IntelliJ: custom code generation templates
- managedobjectcontext - Core Data ManagedObjectContext 和 Private Queue,父上下文的作用
- c# - 使用 Natcorder Video 的帧?
- amazon-web-services - AWS - 缓存预定 lambda 函数的响应
- java - Java Lambda 表达式 参数数据类型
- c# - 第一次运行 asp.net 应用程序
- date - AS3 (animate cc 2018) 为什么日期一直返回未定义?
- android - gridLayout 内的按钮太小
- ios - 如何在 Mac 上打开 TCP&UDP 端口
- php - 在php中重新启动浏览器后无法从会话中获取数据