我在MSSQL中有以下数据:
declare @TEMP table (Period int, Color varchar(20), Rate int)
insert into @TEMP values(201601, 'Blue', 10)
insert into @TEMP values(201602, 'Blue', 10)
insert into @TEMP values(201603, 'Blue', 11)
insert into @TEMP values(201604, 'Red', 11)
insert into @TEMP values(201605, 'Red', 12)
insert into @TEMP values(201606, 'Blue', 13)
insert into @TEMP values(201607, 'Blue', 13)
insert into @TEMP values(201608, 'Blue', 14)
insert into @TEMP values(201609, 'Blue', 14)
insert into @TEMP values(201610, 'Blue', 14)
insert into @TEMP values(201611, 'Blue', 14)
insert into @TEMP values(201612, 'Blue', 14)
SELECT * FROM @TEMP
我想按照颜色进行分组,同时保持“时间顺序”。因此,前3个蓝色记录将独立于最后7个蓝色记录进行分组。 最后,我想选择组中的“最新”行。
输出结果为:
Period | Color | Rate
------ | ----- | ----
201603 | Blue | 11
201605 | Red | 12
201612 | Blue | 14
------ | ----- | ----
答案 0 :(得分:0)
由于窗口功能,我希望您使用的是某些较新版本的SQL Server。
以下是解决方案:
;with x as (
select *, case when lag(color) over(order by period) = color then 0 else 1 end as g
from @temp
),
y as (
select *, sum(g) over(order by period) gg
from x
),
z as (
select *, row_number() over(partition by gg order by period desc) rn
from y
)
select period, color, rate from z where rn = 1