使用Adventureworks2008R2数据库更改输出格式

时间:2018-07-07 23:08:24

标签: sql-server adventureworks

我需要以以下格式更改输出的格式:

43659 709, 711, 712, 714, 716, 771, 772, 773, 774, 776, 777, 778

43660 758, 762

43661 708, 711, 712, 715, 716, 741, 742, 743, 745, 747, 773, 775, 776, 777, 778

如何将Pivot / Unpivot用于以下查询?还是有其他方法可以做到?

Select Distinct ProductID, SalesOrderID 
from Sales.SalesOrderDetail 
Group By SalesOrderID, ProductID 
Order By SalesOrderID, ProductID

Screenshot of my output

1 个答案:

答案 0 :(得分:2)

您确实需要投射productid

SELECT      distinct
            t1.SalesOrderID AS [salesorderid],
            STUFF((    SELECT concat(',' , cast(t2.productid as varchar(10))) AS [text()]
                        FROM Sales.SalesOrderDetail t2
                        WHERE
                        t1.salesorderid = t2.salesorderid
                        order by t2.productid
                        FOR XML PATH('') 
                        ), 1, 1, '' )

            AS [products]
FROM  Sales.SalesOrderDetail t1
where salesorderid in(43659,43660,43661)

salesorderid products
------------ ----------------------------------------------------------
43659        709,711,712,714,716,771,772,773,774,776,777,778
43660        758,762
43661        708,711,712,715,716,741,742,743,745,747,773,775,776,777,778

(3 row(s) affected)