多行到一行sql

时间:2016-08-04 09:50:45

标签: sql sql-server

我有一张桌子如下:
enter image description here

我想查询打印输出如下: enter image description here

2 个答案:

答案 0 :(得分:3)

注意: 请不要downvote 。我知道发布答案的规则,但对于这样的问题,没有机会发布简短答案。我发布它只是为那些想要了解如何实现它的人提供帮助,但不期望即用型解决方案。

我建议阅读这些文章:

PIVOT on two or more fields in SQL Server
Pivoting on multiple columns - SQL Server
Pivot two or more columns in SQL Server 2005

答案 1 :(得分:1)

首先是UNPIVOT,然后是PIVOT。如果每个Pod_ID的行数不总是等于3,那么您需要使用动态SQL。基本样本:

SELECT *
FROM (
    SELECT  Pod_ID,
            Purs + CASE WHEN RN-1 = 0 THEN '' ELSE CAST(RN-1 as nvarchar(10)) END as Purs,
            [Values]
    FROM (
        SELECT  Pod_ID, 
                Pur_Qty, --All columns that will be UNPIVOTed must be same datatype
                Pur_Price, 
                CAST(ETD_Date as int) ETD_Date, -- that is why I cast date to int
                ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as RN
        FROM YourTable
        ) as p1
    UNPIVOT (
        [Values] FOR [Purs] IN(Pur_Qty, Pur_Price, ETD_Date)
    ) as unpvt
    ) as p2
PIVOT (
    MAX([Values]) FOR Purs IN (Pur_Qty,Pur_Price,ETD_Date,Pur_Qty1,Pur_Price1,ETD_Date1,Pur_Qty2,Pur_Price2,ETD_Date2)
) as pvt 

会带给你:

Pod_ID                                  Pur_Qty Pur_Price   ETD_Date    Pur_Qty1    Pur_Price1  ETD_Date1   Pur_Qty2    Pur_Price2  ETD_Date2
F8E2F614-75BC-4E46-B7F8-18C7FC4E5397    24      22          20160820    400         33          20160905    50          44          20160830