然后分组和订单更改以前的值

时间:2016-10-02 22:51:57

标签: sql-server tsql

这是数据:

Event                                           Start           End.             Tag
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:44    9/9/16 10:49     Big
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:50    9/9/16 10:51     Small   
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 12:51    4/4/16 13:58     Big
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 14:04    4/4/16 14:29     Small
11PIC41010.PV 11-PSV-401002W 11-PSV-401002D     4/4/16 16:04    4/4/16 16:45     Big

如何获得以下结果: 我需要按开始时按事件和顺序进行分组,并且只要小到大,就将Big改为Small:

Event                                           Start           End.             Tag
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:44    9/9/16 10:49     Small
10PIC700422.PV 10-PSV-700073A 10-PSV-700073B    9/9/16 10:50    9/9/16 10:51     Small   
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 12:51    4/4/16 13:58     Small
11PIC41010.PV 11-PSV-401002A 11-PSV-401002B     4/4/16 14:04    4/4/16 14:29     Small
11PIC41010.PV 11-PSV-401002W 11-PSV-401002D     4/4/16 16:04    4/4/16 16:45     Big

提前致谢, 小号

1 个答案:

答案 0 :(得分:0)

-- A Demonstrative Table Variabe
Declare @YourTable table ([Event] varchar(100),[Start] DateTime,[End] DateTime, [Tag] varchar(25))
Insert Into @YourTable values
('10PIC700422.PV 10-PSV-700073A 10-PSV-700073B','9/9/16 10:44','9/9/16 10:49','Big'),
('10PIC700422.PV 10-PSV-700073A 10-PSV-700073B','9/9/16 10:50','9/9/16 10:51','Small'),
('11PIC41010.PV 11-PSV-401002A 11-PSV-401002B','4/4/16 12:51','4/4/16 13:58','Big'),
('11PIC41010.PV 11-PSV-401002A 11-PSV-401002B','4/4/16 14:04','4/4/16 14:29','Small'),
('11PIC41010.PV 11-PSV-401002W 11-PSV-401002D','4/4/16 16:04','4/4/16 16:45','Big')

-- The Actual Query 
Select [Event]
      ,[Start]
      ,[End] 
      ,[Tag] = case when Tag='Big' and 'Small' = Lead(Tag,1,Tag) over (Partition By Event Order By Start) then 'Small' else tag end
 From  @YourTable

可能是巧合,但是如果没有CASE

,你碰巧会得到相同的结果
,[Tag] = Lead(Tag,1,Tag) over (Partition By Event Order By Start)