如何创建包含有关下一条或上一条记录的信息的视图?

How can I create a view with information about the next or previous record?

谁能帮我用 "create view" 代码得到下面的结果集。

CREATE VIEW MyView AS (SELECT .....FROM Movements ...)

我有一个 table "Movements" 这样的:

 
ID  name    City        from date
U1  Smith   New York    1 jan 2000
U1  Smith   Austin      1 dec 2001
U1  Smith   Scottsdale  1 jul 2002
U2  Jack    Houston     1 sep 2000
U2  Jack    New York    1 nov 2000
U3  Jane    Knoxville   1 feb 2000
U3  Jane    Richmond    1 mrt 2001
U3  Jane    San Diego   1 jan 2002
U3  Jane    Oak Park    1 oct 2004

我想看一下人的动向

我可能有 2 个结果集。我知道第一个有列数限制。

我喜欢查看每个结果集

结果集 1:

ID  name    city 1      city 2    city 3      city 4
U1  Smith   New York    Austin    Scottsdale    
U2  Jack    Houton      New York        
U3  Jane    Knoxville   Richmond  San Diego   Oak Park

或者

结果集2

ID  name    City        from date   to city
U1  Smith   New York    1 jan 2000  Austin
U1  Smith   Austin      1 dec 2001  Scottsdale
U1  Smith   Scottsdale  1 jul 2002  
U2  Jack    Houston     1 sep 2000  New York
U2  Jack    New York    1 nov 2000  
U3  Jane    Knoxville   1 feb 2000  Richmond
U3  Jane    Richmond    1 mrt 2001  San Diego
U3  Jane    San Diego   1 jan 2002  Oak Park
U3  Jane    Oak Park    1 oct 2004  

您可以对结果集 2 使用 LEAD window 函数

SELECT ID,
       NAME,
       City,
       [from date],
       toCity = Coalesce(Lead(City)over(Partition by ID, name order by [from date]),'')
FROM   Yourtable

结果集 1 需要 dynamic pivot

DECLARE @sql      NVARCHAR(max),
        @col_list VARCHAR(max)

SET @col_list =Stuff((SELECT DISTINCT ','+ Quotename('City '+ Cast(Row_number()OVER(partition BY ID ORDER BY [from date]) AS VARCHAR(50)))
                      FROM   Yourtable
                      FOR xml path('')), 1, 1, '')
SET @sql = '
select * 
    from (select ID,name,City,city_num =''City ''+ cast(row_number()over(partition by ID order by [from date]) as varchar(50))  
            from Yourtable) a
    pivot (max(city) for city_num in ('+ @col_list + ')) pv'

EXEC Sp_executesql @sql