从表中选择3行组中的行作为单行

时间:2018-06-14 22:41:35

标签: sql-server

假设我有一张桌子:

Row       Title       Date
----      -----       ----
1         Title 1     1/1/2018
2         Title 2     1/2/2018
3         Title 3     1/3/2018
4         Title 4     1/4/2018
5         Title 5     1/5/2018
6         Title 6     1/6/2018

我想将数据选择为每行包含三行的行(如果有意义的话)。例如像这样

Row1   Title1   Date1      Row2   Title2   Date2      Row3   Title3   Date3
-------------------------------------------------------------------------------
1      Title 1  1/1/2018   2      Title 2  1/2/2018   3      Title 3  1/3/2018
4      Title 4  1/4/2018   5      Title 5  1/5/2018   6      Title 6  1/6/2018

这可能吗?我尝试过使用临时表但不成功:/

1 个答案:

答案 0 :(得分:1)

WITH
    numbered AS (
        SELECT  Row ,
                Title ,
                Date ,
                ROW_NUMBER() OVER (ORDER BY Row) AS RowNumber
        FROM    Table
    )
SELECT  n1.Row AS Row1 ,
        n1.Title AS Title1 ,
        n1.Date AS Date1 ,
        n2.Row AS Row2 ,
        n2.Title AS Title2 ,
        n2.Date AS Date2 ,
        n3.Row AS Row3 ,
        n3.Title AS Title3 ,
        n3.Date AS Date3
FROM    numbered n1
LEFT OUTER JOIN numbered n2 ON n2.RowNumber = n1.RowNumber + 1
LEFT OUTER JOIN numbered n3 ON n3.RowNumber = n1.RowNumber + 2
WHERE   (n1.RowNumber - 1) % 3 = 0