SQL Server查询“第二天的更改”

时间:2018-10-01 19:49:00

标签: sql sql-server database

我有一个如下数据集:

Name  Date      Type
Alex  18/1/5     A
Bob   17/12/31   D
Alex  18/1/1     B
Alex  18/1/8     A
Bob   17/8/31    D
Bob   18/3/31    C
Bob   18/6/30    E

我要执行以下操作: 对于每个名称,按日期排序,然后找到排序结果之间的类型变化。 结果应如下所示:

  Name  DateBefore DateAfter TypeBefore TypeAfter
  Alex  18/1/1     18/1/5    B          A
  Bob   17/12/31   18/3/31   D          C
  Bob   18/3/31    18/6/30   C          E

如何通过SQL查询实现这一目标?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,则可以尝试在子查询中使用LEAD窗口函数,然后获取此类型不等于nextType行。

CREATE TABLE T(
  Name VARCHAR(50),
  [Date] DATE,
  [Type] VARCHAR(5)

);




INSERT INTO T VALUES ('Alex','2018/01/5','A');
INSERT INTO T VALUES ('Bob','2017/12/31','D');
INSERT INTO T VALUES ('Alex','2018/01/1','B');
INSERT INTO T VALUES ('Alex','2018/01/8','A');
INSERT INTO T VALUES ('Bob','2017/08/31','D');
INSERT INTO T VALUES ('Bob','2018/03/31','C');
INSERT INTO T VALUES ('Bob','2018/06/30','E');

查询1

SELECT Name,
      [Date] 'DateBefore',
      nextDt 'DateAfter',
      [Type] 'TypeBefore' ,
      nextType 'TypeAfter'
FROM 
(
select  *,LEAD([Date]) over(partition by Name order by [Date])  nextDt
          ,LEAD([Type]) over(partition by Name order by [Date]) nextType
from t
) t1
where [Type] <> nextType

Results

| Name | DateBefore |  DateAfter | TypeBefore | TypeAfter |
|------|------------|------------|------------|-----------|
| Alex | 2018-01-01 | 2018-01-05 |          B |         A |
|  Bob | 2017-12-31 | 2018-03-31 |          D |         C |
|  Bob | 2018-03-31 | 2018-06-30 |          C |         E |

答案 1 :(得分:0)

据我了解,下面的查询将起作用;

SELECT        
    t1.Name AS NameOfPerson, 
    t1.Date AS DateBefore,
    t1.Type AS TypeBefore,
    (
        SELECT TOP 1 t2.Date 
        FROM PeopleTable AS t2 
        WHERE t2.Name = T1.Name AND t2.Date>t1.Date
        ORDER BY t2.Date 
    ) AS DateAfter,
    (
        SELECT TOP 1 t2.Type 
        FROM PeopleTable AS t2 
        WHERE t2.Name = T1.Name AND t2.Date>t1.Date
        ORDER BY t2.Date 
    ) AS TypeAfter
FROM PeopleTable AS t1 
ORDER BY Date ASC

查询可以与您的示例输出匹配来优化。