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

Change the format of the output using the adventureworks2008R2 database

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

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

您确实需要转换 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)