我在SQL Server数据库中有一个表,它每天存储历史数据。结构如下所示:
UploadDate TypeID Value1 Value2
-------------------------------------------
2012-01-08 1 NEG 1998-02-05
2012-01-08 2 NEG 1999-02-09
2012-01-08 3 STABLE 1997-02-06
2012-02-08 1 NEG 1998-02-05
2012-02-08 2 NEG 1999-02-09
2012-03-08 1 POS 2012-03-08
2012-03-08 2 STABLE 2012-01-08
正如您在上面看到的TypeID
1& 2,Value1
和Value2
已于2012-03-08更改
我的要求是,我必须只显示那些从以前的值改变的行。
在这种情况下,TypeID
1& 2已经改变,它应该显示当前和最接近的先前值。对于TypeID
3,因为它没有改变,它只会显示最新的值。结果集如下所示:
UploadDate TypeID Value1 Value2
-------------------------------------------
2012-01-08 3 STABLE 1997-02-06
2012-02-08 1 NEG 1998-02-05
2012-02-08 2 NEG 1999-02-09
2012-03-08 1 POS 2012-03-08
2012-03-08 2 STABLE 2012-01-08
知道如何使用SQL解决这个问题吗?
答案 0 :(得分:10)
Uninspired版本在有序集上使用自联接来检查同一typeid的按时间顺序排列的前一行的值。如果没有前一行或值不同,则输出该行。
; with numbered as (
select *,
row_number() over (order by typeid, uploaddate) rn
from table1
)
select n1.*
from numbered n1
left join numbered n2
on n1.TypeID = n2.TypeID
and n1.rn + 1 = n2.rn
where (n2.rn is null
or n1.value1 <> n2.value1
or n1.value2 <> n2.value2)
order by typeid, uploaddate
Here is Sql Fiddle with example
更新:另一种不需要自联接但需要分组的变体。同一typeid的每个时间轴,value1和value2都被赋予唯一的group_number,稍后将用于提取该组的max(uploaddate)。
; with numbered as (
select *,
row_number() over (order by typeid, uploaddate)
- row_number() over (partition by typeid, value1, value2
order by uploaddate) group_number
from table1
)
select max(uploaddate) uploaddate, typeid, value1, value2
from numbered
group by typeid, value1, value2, group_number
order by typeid, uploaddate