0

我的 SQL Server 查询如下所示:

SELECT OrderId, Productcode, Quantity, ProductName, options 
FROM OrderDetails 
ORDER BY Productcode DESC

输出以下结果:(请检查此图片).

There is a table for Options with the following fields and data types
optionsdesc(nvarchar) , id(float)

我想修改查询,使其结果包含一列option,第二列包含该特定选项的销售数量,第三个订单用逗号分隔,如下所示。结果应如下所示。Options field is nvarchar(255)

options                           Count      Order id   
---------------------------------------------------------------------------------
[Size 15ml bottlle ]                 3          1296,1341, 1384
[Nicotine Level:12 mg Nicotnie ]     2          1296,1312
[Size 30ml bottlle ]                 4          1312,1334, 1344, 1391
4

1 回答 1

1

假设如下:

  • 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)

我希望这有帮助。

于 2013-08-09T15:25:53.523 回答