[英]Group count values in comma separated field in SQL Server 2008
我有一個帶列product
的users
表。
我想算一下我桌子上有多少種產品
Users
表
+----------+
| Products |
+----------+
| A |
| B |
| A,c |
| C,B,A |
| D |
+----------+
即A的計數是:3,B的計數是:2,C的計數是:2,D的計數是: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
使用遞歸查詢-遞歸拆分為2列l
包含不帶逗號的條目和r
的Products
尾部,之后使GROUP BY
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.