假设我有一个返回的查询
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)"
我连接的地方:
进入"细节" NVarchar结果??
答案 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