2013-10-30 82 views

回答

1

请尝试:

SELECT Products, COUNT(Products) 
FROM(
    SELECT 
     Split.a.value('.', 'VARCHAR(100)') AS Products 
    FROM 
    (
     SELECT 
      CAST ('<M>' + REPLACE(Products, ',', '</M><M>') + '</M>' AS XML) AS CVS 
     from YourTable 
    ) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a) 
)x GROUP BY Products 
0

使用递归查询 - STE递归分割的2个柱体P - l - 包含没有逗号和r入门 - 中Products尾,之后,使GROUP BY通过l柱:

WITH expandProd as(
    SELECT 
     CASE 
      WHEN charindex(',', Products) < 1 THEN Products 
      ELSE LEFT(Products, charindex(',', Products)-1) 
     END as l, -- the column without comma 
     CASE 
      WHEN charindex(',', Products) < 1 THEN NULL 
      ELSE RIGHT(Products, LEN(Products) - charindex(',', Products)) 
     END as r -- the column with tail 
    FROM prods 
    UNION ALL --recursive query that enters again to itself 
    SELECT 
     CASE 
      WHEN charindex(',', r) < 1 THEN r 
      ELSE LEFT(r, charindex(',', r)-1) 
     END as l, 
     CASE 
      WHEN charindex(',', r) < 1 THEN NULL 
      ELSE RIGHT(r, LEN(r) - charindex(',', r)) 
     END as r 
    FROM expandProd 
WHERE r is not null --small optimization 
) 
SELECT l, COUNT(l) 
    FROM expandProd 
    GROUP BY l 
相关问题