跨多个行连接多个字段

时间:2015-02-27 02:58:47

标签: sql sql-server tsql

假设我有一个返回的查询

OrderID   Date           Product    Count
  1       2015-01-01     "Bread"      1
  2       2015-02-02     "Water"      2
  2       2015-02-02     "Bread"      7
  2       2015-02-02     "Soap"       3

如何使此查询返回连接多个列的2条记录(按ID分组)

OrderID   Date           Detail
  1       2015-01-01     "Bread (1)"
  2       2015-02-02     "Bread (7), Soap (3), Water (2)"

我连接的地方:

  1. 产品名称及其计数值(括号内)
  2. 按产品名称排序
  3. 进入"细节" NVarchar结果??

2 个答案:

答案 0 :(得分:2)

我将让你处理删除的逗号。

CREATE TABLE orders ([OrderID] INT,[Date] DATE,[Product] VARCHAR(10),[Count] INT)

INSERT INTO orders
VALUES (1,'2015-01-01','Bread',1),
        (2,'2015-02-02','Water',2),
        (2,'2015-02-02','Bread',7),
        (2,'2015-02-02','Soap',3)

SELECT
    OrderID,
    [Date],
    (
        SELECT DISTINCT 
            [Product] + '(' + CONVERT(VARCHAR,[Count]) + '), '
        FROM 
            orders o1
        WHERE o1.OrderID = o.OrderID
        FOR XML PATH('')    
     ) Detail
FROM orders o
GROUP BY OrderID, [Date]

答案 1 :(得分:2)

你没有提到相同的orderid日期是否不同,那么会发生什么。

试试这个,

Declare @orders TABLE ([OrderID] INT,[Date] DATE,[Product] VARCHAR(10),[Count] INT)

    INSERT INTO @orders
    VALUES (1,'2015-01-01','Bread',1),
            (2,'2015-02-02','Water',2),
            (2,'2015-02-02','Bread',7),
            (2,'2015-02-02','Soap',3),
                (2,'2015-03-02','Soap',3)

    ;WITH CTE
    AS (
        SELECT *
            ,ROW_NUMBER() OVER (
                PARTITION BY orderid
                ,[date] ORDER BY [date]
                ) rn
        FROM @orders
        )
    SELECT OrderID
        ,[date]
        ,stuff((
                SELECT ',' + Product + ' ( ' + CONVERT(VARCHAR,[Count]) + ' ) '
                FROM cte
                WHERE orderid = a.OrderID
                    AND [Date] = a.[Date]
                FOR XML path('')
                ), 1, 1, '') [details]
    FROM CTE A
    WHERE rn = 1