我有一个users
表,其中包含product
列。
我想知道我桌上有多少产品
Users
表
+----------+
| Products |
+----------+
| A |
| B |
| A,c |
| C,B,A |
| D |
+----------+
即。 A的计数为:3,B的计数为:2,C的计数为:2,D的计数为:1
答案 0 :(得分: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
答案 1 :(得分:0)
使用递归查询 - 在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