字段中的SQL计数ID

时间:2013-05-22 08:52:29

标签: sql sql-server count

我的表中包含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

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

试试这个 -

<强>查询:

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

查询费用

proff

答案 1 :(得分:3)

试试这个:

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

我喜欢Devart的答案,因为执行速度更快。以下是修改后的earlier answer以满足您的需求:

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