SQL Server查询以显示选项值和计数

时间:2013-08-09 14:30:28

标签: sql sql-server sql-server-2005

我的SQL Server查询如下所示:

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

输出以下结果:(please check this image)

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

1 个答案:

答案 0 :(得分: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

您可以尝试 here

我的示例数据是:

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)

我希望这会有所帮助。