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

时间:2017-12-29 15:54:35

标签: sql-server create-view

有人可以帮助我创建视图"代码来获取下面的结果集。

创建视图MyView AS(SELECT ..... FROM Movements ...)

我有一张桌子" 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

或者

Resultset2

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  

1 个答案:

答案 0 :(得分:0)

您可以将LEAD窗口函数用于结果集2

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