在SQL Server中将多行显示为一行

时间:2017-05-21 00:08:57

标签: sql-server sql-server-2008 pivot ssrs-2008 reportbuilder3.0

请参阅以下示例:

enter image description here

我想将所有这些行合并为一行,请注意行数是动态的!

输出应该是这样的:

enter image description here

谢谢

1 个答案:

答案 0 :(得分:1)

示例

Select Count=[C1],Pays=[P1],Count=[C2],Pays=[P2],Count=[C3],Pays=[P3],Count=[C4],Pays=[P4]
From (
        Select B.*
         From  (
                Select *,RN = Row_Number() over (Order By Pays)
                 From  YourTable
               ) A
         Cross Apply (values ('P'+cast(A.RN as varchar(25)),A.Pays)
                            ,('C'+cast(A.RN as varchar(25)),cast(A.Count as varchar(50)))
                     ) B (Item,Value)
     ) A
 Pivot (max(value) For [Item] in ([C1],[P1],[C2],[P2],[C3],[P3],[C4],[P4]) ) p

<强>返回

enter image description here

如果有帮助,生成的SQL看起来像这样:

A