SQL透视图将行平整为列

Sco*_*ott 4 t-sql sql-server

我有一个看起来像这样的源表:

+--------------+----------+------+------------+-----------+
| vehicleindex | parentid | year |    make    |   model   |
+--------------+----------+------+------------+-----------+
|            1 |        1 | 2007 | TOYOTA     | SIENNA LE |
|            2 |        1 | 2005 | VOLKSWAGEN | JETTA GLS |
+--------------+----------+------+------------+-----------+
Run Code Online (Sandbox Code Playgroud)

我想从此表中进行选择,以使输出如下所示:

+-------+--------+-----------+-------+------------+-----------+
| year1 | make1  |  model1   | year2 |   make2    |  model2   |
+-------+--------+-----------+-------+------------+-----------+
|  2007 | TOYOTA | SIELLA LE |  2005 | VOLKSWAGEN | JETTA GLS |
+-------+--------+-----------+-------+------------+-----------+
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点具有枢轴SQL Server数据库吗?源表中将始终有1或2辆车。在那里的1号车的情况下,我希望Year2Make2并且Model2NULL

Joh*_*tti 6

类似于SQLZim的答案。唯一的区别是所述窗口函数ROW_NUMBER()用于以防万一vehicleindex不是一致的1和2。

Select year1  = max(case when RN=1 then [year] end)
      ,make1  = max(case when RN=1 then make end)
      ,model1 = max(case when RN=1 then model end)
      ,year2  = max(case when RN=2 then [year] end)
      ,make2  = max(case when RN=2 then make end)
      ,model2 = max(case when RN=2 then model end)
 From (
        Select *
              ,RN = Row_Number() over (Partition By parentid Order By vehicleindex)
         From  YourTable
      ) A
 Group By parentid 
Run Code Online (Sandbox Code Playgroud)

编辑:选项2-使用PIVOT

Select *
From (
        Select parentid
              ,item     = concat(B.item,Dense_Rank() over (Partition By parentid Order By vehicleindex))
              ,value
         From  YourTable
         Cross Apply ( values ('year' ,cast(Year as varchar(100)))
                             ,('make' ,make)
                             ,('model',model)
                      ) B (item,value)
     ) A
 Pivot (max(value) For [item] in ([year1],[make1],[model1],[year2],[make2],[model2]) ) p
Run Code Online (Sandbox Code Playgroud)