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

してみてください:

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を含み、その後、列で作成:rProductsGROUP 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 に答える