2

我有一个users带有列的表product

我想计算我的表中有多少产品

Users桌子

+----------+
| Products |
+----------+
| A        |
| B        |
| A,c      |
| C,B,A    |
| D        |
+----------+

即 A 的计数为:3,B 的计数为:2,C 的计数为:2,D 的计数为:1

4

2 回答 2

1

Please try:

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
于 2013-10-30T09:49:47.860 回答
0

使用递归查询 - 在 2 列上拆分的递归步骤l- 包含不带逗号的条目和r- 的尾部Products,之后GROUP BYl列生成:

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
于 2013-10-30T10:10:58.227 回答