我有张表是:rid     groupid
 1      118,3,1
 2      149,2,4
 3      118,4,1
 4      200,4,2
 5      204,8,2
 6      304,5,2
我传进去参数为"4",如何得到表里存在4的总数。
用like '%4%'  模糊匹配这样会有问题。id为6的也会得到。所以这样不行。
我有个分隔函数了  f_split('118,3,1',',') 分隔后得到 
118
3
1
然后4跟这个3个数对比。有存在数量就加1
帮忙把这个SQL写出来TY

解决方案 »

  1.   

    select * from tb where exists(select 1 from  f_split(groupid) b where col = 4)
      

  2.   

    ','+groupid+',' like '%,4,%'
      

  3.   

    最好把你的 f_split函数贴出来,或者把显示的效果贴出来
    而且你的说的“有存在数量就加1”,这个加1是正对那个字段加1??、
      

  4.   


    f_split是个存储过程
    执行后报'groupid' 不是可以识别的 OPTIMIZER LOCK HINTS 选项。
      

  5.   


    create function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10))
    returns @temp table(a varchar(100))
    --实现split功能 的函数
    --date    :2010-7-30
    as 
    begin
        declare @i int
        set @SourceSql=rtrim(ltrim(@SourceSql))
        set @i=charindex(@StrSeprate,@SourceSql)
        while @i>=1
        begin
            insert @temp values(left(@SourceSql,@i-1))
            set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
            set @i=charindex(@StrSeprate,@SourceSql)
        end
        if @SourceSql<>'' 
           insert @temp values(@SourceSql)
        return 
    end
      

  6.   


    declare @t table (irid int, groupid varchar(50))
    insert @t
    select 1 ,'118,4,4' union all
    select 2 ,'149,2,4' union all
    select 3 ,'118,4,1' union all
    select 4 ,'200,4,2' union all
    select 5 ,'204,8,2' union all
    select 6 ,'304,5,2'
    ;with cte as(select irid,convert(xml,'<root><row>'+replace(groupid,',','</row><row>')+'</row></root>')  as v from @t)select irid,v.value('count(/root/row[text()=4])','INT')  as num from cte
    (6 行受影响)
    irid        num
    ----------- -----------
    1           2
    2           1
    3           1
    4           1
    5           0
    6           0(6 行受影响)
      

  7.   

    ordeclare @t table (irid int, groupid varchar(50))
    insert @t
    select 1 ,'118,4,4' union all
    select 2 ,'149,2,4' union all
    select 3 ,'118,4,1' union all
    select 4 ,'200,4,2' union all
    select 5 ,'204,8,2' union all
    select 6 ,'304,5,2'
    ;with cte as(select irid,convert(xml,'<root><row>'+replace(groupid,',','</row><row>')+'</row></root>')  as v from @t)select irid,v.value('count(/root/row[text()=4])','INT')  as num from cte
    where v.exist('(/root/row[text()=4])')=1(6 行受影响)
    irid        num
    ----------- -----------
    1           2
    2           1
    3           1
    4           1(4 行受影响)
      

  8.   

    搞笑这样既然可以了!
    select count(*) from tablename where groupid like '%,4,%' or groupid like '4,%' or groupid like '%,4'