假设如下:
- 该列
options
始终具有[...][...](两个值)。
- 该列
quantity
将包含该组的总和。
也许这个查询会很有用(这适用于 Sql 2012-2008,但也适用于 2005):
WITH temp AS(
SELECT
quantity,
orderid,
PARSENAME(REPLACE(REPLACE(REPLACE(options,'][','.'),'[',''),']',''),1) AS first,
PARSENAME(REPLACE(REPLACE(REPLACE(options,'][','.'),'[',''),']',''),2) AS second
FROM OrderDetails
),
concatenate_list AS (
SELECT
first AS options,
STUFF((SELECT ', ' + CAST(x.orderid AS VARCHAR)
FROM temp x
WHERE x.first = y.first
FOR XML PATH('')),1,1,''
) AS list
FROM temp y
GROUP BY y.first
UNION
SELECT
second as options,
STUFF((SELECT ', ' + CAST(x.orderid AS VARCHAR)
FROM temp x
WHERE x.second = y.second
FOR XML PATH('')),1,1,''
) AS list
FROM temp y
GROUP BY y.second
)
SELECT
cl.options AS options,
SUM(t.quantity) AS quantity,
cl.list AS orderid
FROM temp t
LEFT JOIN concatenate_list cl ON cl.options = t.first
GROUP BY cl.options,cl.list
UNION
SELECT
cl.options AS options,
SUM(t.quantity) AS quantity,
cl.list AS orderid
FROM temp t
LEFT JOIN concatenate_list cl ON cl.options = t.second
GROUP BY cl.options,cl.list
你在这里试试这个。
我的示例数据是:
CREATE TABLE OrderDetails(
options VARCHAR(100),
quantity int,
orderid int
)
INSERT INTO OrderDetails VALUES('[Size 15ml bottlle][Nicotine Level:12 mg Nicotnie]',1,1296)
INSERT INTO OrderDetails VALUES('[Size 15ml bottlle][Nicotine Level:12 mg Nicotnie]',0,1391)
INSERT INTO OrderDetails VALUES('[Size 15ml bottlle][Nicotine Level:0 mg Nicotnie]',1,1122)
INSERT INTO OrderDetails VALUES('[Size 15ml bottlle][Nicotine Level:6 mg Nicotnie]',2,1196)
INSERT INTO OrderDetails VALUES('[Size 30ml bottlle][Nicotine Level:5 mg Nicotnie]',1,4563)
INSERT INTO OrderDetails VALUES('[Size 30ml bottlle][Nicotine Level:4 mg Nicotnie]',2,2123)
INSERT INTO OrderDetails VALUES('[Size 30ml bottlle][Nicotine Level:0 mg Nicotnie]',1,6754)
我希望这有帮助。