如何使用Lag / Max窗函数添加常量?

时间:2016-09-14 04:51:54

标签: sql-server tsql amazon-redshift window-functions

请参阅下面的样本表。我的表有ID,ID_Type,Lag和Row_Num。我需要在下面创建“New_Col”列。我接近使用MAX窗口功能,但我还没有成功。任何帮助都将非常感激 - 如果窗口功能不是要走的路,我绝对愿意接受建议。

以下是我用来到下面的示例表的SQL:

SELECT ID,
       ID_TYPE,
       LAG(ID_TYPE) OVER (ORDER BY Row_Num) AS Lag,
       Row_Num
FROM (SELECT ID,
             CASE WHEN ID LIKE '%Exc%' 
                  THEN ID
             END AS ID_Type,
             Row_Num
      FROM Source_Table)

样本表:

ID       ID_Type  Lag       Row_Num
Exc      Exc                1
10R46             Exc       2
10R46                       3
100R91                      4
Non_Exc  Non_Exc            5 
10R91             Non_Exc   6
10M95                       7

期望的输出:

ID       ID_Type  Lag       New_Col  Row_Num
Exc                         Exc      1
10R46    Exc                Exc      2
10R46             Exc       Exc      3
100R91                      Exc      4
Non_Exc  Non_Exc            Non_Exc  5 
10R91             Non_Exc   Non_Exc  6
10M95                       Non_Exc  7

2 个答案:

答案 0 :(得分:0)

一种方法是生成范围键

Declare @YourTable table (ID varchar(50),ID_Type varchar(50),Lag varchar(50),Row_Num int)
Insert into @YourTable values
('Exc','Exc','',1),
('10R46','','Exc',2),
('10R46','','',3),
('100R91','','',4),
('Non_Exc','Non_Exc','',5),
('10R91','','Non_Exc',6),
('10M95','','',7)

;with cteR1 as (Select ID_Type,R1=min(Row_Num) from @YourTable Where ID_Type<>'' Group by ID_Type
   ), cteR2 as (Select A.ID_Type,A.R1,R2=isnull(min(B.R1),9999)-1 From cteR1 A Left Join cteR1 B on (B.R1>A.R1) Group By A.ID_Type,A.R1)
Select A.ID
      ,A.ID_Type
      ,A.Lag 
      ,New_Col=B.ID_Type
      ,A.Row_Num
 From @YourTable A
 Join cteR2 B on Row_Num between R1 and R2
 Order By Row_Num

返回

ID      ID_Type Lag     Row_Num New_Col
Exc     Exc             1       Exc
10R46           Exc     2       Exc
10R46                   3       Exc
100R91                  4       Exc
Non_Exc Non_Exc         5       Non_Exc
10R91           Non_Exc 6       Non_Exc
10M95                   7       Non_Exc

答案 1 :(得分:0)

将IGNORE NULLS规范添加到LAG窗口功能可以实现我的目标。

"c = a + b"

返回:

SELECT ID,
       ID_TYPE,
       LAG(ID_TYPE IGNORE NULLS) OVER (ORDER BY Row_Num) AS Lag,
       Row_Num
FROM (SELECT ID,
             CASE WHEN ID LIKE '%Exc%' 
                  THEN ID
             END AS ID_Type,
             Row_Num
      FROM Source_Table)