1

我有一个表,其中包含字段中的 ID。看起来像:

FieldName
-------------------------
1,8,2,3,4,10,5,9,6,7
-------------------------
1,8
-------------------------
1,8

我需要计算这些 ID 以获得结果:

ID | Count
---|------
1 | 3
8 | 3
2 | 1
3 | 1

有任何想法吗?

谢谢!

4

2 回答 2

2

Try this :

Declare  @demo table(FieldName varchar(100))

insert into @demo values('1,8,2,3,4,10,5,9,6,7')
insert into @demo values('1,8')
insert into @demo values('1,8')


select ID, COUNT(id) ID_count from 
(SELECT 
     CAST(Split.a.value('.', 'VARCHAR(100)') AS INT) AS ID 
FROM  
(
SELECT CAST ('<M>' + REPLACE(FieldName, ',', '</M><M>') + '</M>' AS XML) AS ID  
    FROM  @demo
) AS A CROSS APPLY ID.nodes ('/M') AS Split(a)) q1
group by ID

I like Devart's answer because of the faster execution. Here is a modified earlier answer to suite your need :

Declare @col varchar(200)

SELECT
@col=(
        SELECT FieldName + ','
        FROM @demo c

        FOR XML PATH('')
      );


;with demo as(


select cast(substring(@col,1,charindex(',',@col,1)-1) AS INT) cou,charindex(',',@col,1) pos

  union all 
  select cast(substring(@col,pos+1,charindex(',',@col,pos+1)-pos-1)AS INT) cou,charindex(',',@col,pos+1) pos
  from demo where pos<LEN(@col))
select  cou ID, COUNT(cou) id_count from demo    
group by cou
于 2013-05-22T09:01:34.920 回答
2

试试这个——

询问:

SET NOCOUNT ON;

DECLARE @temp TABLE (txt VARCHAR(8000))

INSERT INTO @temp (txt)
VALUES ('1,8,2,3,4,10,5,9,6,7'), ('1,8'), ('1,8')

SELECT 
      t.ID
    , [Count] = COUNT(1)
FROM (
    SELECT
          ID = 
            SUBSTRING(
                  t.string
                , number + 1
                , ABS(CHARINDEX(',', t.string, number + 1) - number - 1)
            )
    FROM (
        SELECT string = (
            SELECT ',' + txt
            FROM @temp
            FOR XML PATH(N''), TYPE, ROOT).value(N'root[1]', N'NVARCHAR(MAX)')
    ) t
    CROSS JOIN [master].dbo.spt_values n
    WHERE [type] = 'p'
        AND number <= LEN(t.string) - 1
        AND SUBSTRING(t.string, number, 1) = ','
) t
GROUP BY t.ID
ORDER BY [Count] DESC

输出:

ID    Count
----- -----------
1     3
8     3
9     1
10    1
2     1
3     1
4     1
5     1
6     1
7     1

查询费用:

教授

于 2013-05-22T08:56:37.213 回答