将值复制到下面的行中,直到在SQL中找到更大的值

时间:2018-09-18 21:18:17

标签: sql sql-server

我一直在尝试在“ episode”中复制第一个顺序值,直到找到另一个值而不是它本身(请参见下面的“ episode_final”列),而不会带来太多的运气。该逻辑应按SQL Server 2012中按日期排序的ID对数据进行分区。将不胜感激。

sample_edited

1 个答案:

答案 0 :(得分:1)

您可以尝试使用LEAD窗口函数获取下一个值episode

然后使用CASE WHEN检查episode> nextVal确实增加1。

CREATE TABLE T(
  id varchar(50),
  date date,
  episode int
);

INSERT INTO T VALUES (123,'2018-01-01',1); 
INSERT INTO T VALUES (123,'2018-01-02',1); 
INSERT INTO T VALUES (123,'2018-01-10',1); 
INSERT INTO T VALUES (123,'2018-01-11',1); 
INSERT INTO T VALUES (123,'2018-01-12',1); 
INSERT INTO T VALUES (123,'2018-01-20',2);  
INSERT INTO T VALUES (123,'2018-03-20',1);  
INSERT INTO T VALUES (123,'2018-05-01',1); 
INSERT INTO T VALUES (123,'2018-05-10',3); 
INSERT INTO T VALUES (123,'2018-05-20',1); 
INSERT INTO T VALUES (345,'2018-06-20',1);  
INSERT INTO T VALUES (345,'2018-07-21',1);  
INSERT INTO T VALUES (345,'2018-07-22',2);  

查询1

    SELECT  t1.Id,
           t1.Date,
           t1.episode,
         (SUM(CASE WHEN episode> coalesce(nextVal,preVal) THEN 1 ELSE 0 END) over (partition by id order by [date]) + 1)  episode_final
    FROM (
      SELECT T.*,LEAD(episode) over (partition by id  order by  [date]) nextVal,
      LAG(episode) over (partition by id  order by  [date]) preVal
      FROM T 
    )t1

Results

|  Id |       Date | episode | episode_final |
|-----|------------|---------|---------------|
| 123 | 2018-01-01 |       1 |             1 |
| 123 | 2018-01-02 |       1 |             1 |
| 123 | 2018-01-10 |       1 |             1 |
| 123 | 2018-01-11 |       1 |             1 |
| 123 | 2018-01-12 |       1 |             1 |
| 123 | 2018-01-20 |       2 |             2 |
| 123 | 2018-03-20 |       1 |             2 |
| 123 | 2018-05-01 |       1 |             2 |
| 123 | 2018-05-10 |       3 |             3 |
| 123 | 2018-05-20 |       1 |             3 |
| 345 | 2018-06-20 |       1 |             1 |
| 345 | 2018-07-21 |       1 |             1 |
| 345 | 2018-07-22 |       2 |             2 |