棘手的SQL查询需要搜索包含

时间:2012-09-08 05:47:10

标签: sql sql-server sql-server-2008

我有这样的数据:

表格中的发明人专栏

Hundley; Edward; Ana
Isler; Hunsberger
Hunsberger;Hundley

名称以;分隔。我想编写一个总结计数的SQL查询。

EG。结果应该是:

Hundley     2
Isler       1
Hunsberger  2
Edward      1
Ana         1

我可以做一个小组,但这不是一个简单的小组,你可以看到。关于如何获得此输出的任何想法/想法?

修改:更改了结果,因此不会产生任何混淆,即行只包含2个名称。

5 个答案:

答案 0 :(得分:1)

你可以看看这个。如果你有很多数据,我当然不推荐这种方式,但你可以做一些修改并使用它,它就像一个魅力!

这是支持无限拆分的新代码:

Declare @Table  Table   (
    Name    Nvarchar(50)
);

Insert  @Table  (
    Name
)   Select  'Hundley; Edward; Anna'
Union   Select  'Isler; Hunsberger'
Union   Select  'Hunsberger; Hundley'
Union   Select  'Anna'
;

With    Result  (
    Part
,   Remained
,   [Index]
,   Level
)   As  (
    Select  Case    When    CharIndex(';', Name, 1) =   0
            Then    Name
            Else    Left(Name, CharIndex(';', Name, 1) - 1)
        End
    ,   Right(Name, Len(Name) - CharIndex(';', Name, 1))
    ,   CharIndex(';', Name, 1)
    ,   1
        From    @Table
Union   All
    Select  LTrim(
        Case    When    CharIndex(';', Remained, 1) =   0
            Then    Remained
            Else    Left(Remained, CharIndex(';', Remained, 1) - 1)
        End
    )
    ,   Right(Remained, Len(Remained) - CharIndex(';', Remained, 1))
    ,   CharIndex(';', Remained, 1)
    ,   Level
    +   1
        From    Result
        Where   [Index] <>  0
)   Select  Part
    ,   Count(*)
        From    Result
        Group   By  Part

干杯

答案 1 :(得分:1)

;with cte as  
( 
    select 1 as Item, 1 as Start, CHARINDEX(';',inventors, 1) as Split, Inventors from YourInventorsTable
    union all 
    select cte.Item+1, cte.Split+1, nullif(CHARINDEX(';',inventors, cte.Split+1),0), inventors as Split 
    from cte 
    where cte.Split<>0   
)    

select rTRIM(lTRIM(SUBSTRING(inventors, start,isnull(split,len(inventors)+1)-start))), count(*)
from cte  
group by rTRIM(lTRIM(SUBSTRING(inventors, start,isnull(split,len(inventors)+1)-start)))

答案 2 :(得分:1)

您可以创建split function来分割col值

select splittedValues.items,count(splittedValues) from table1
cross apply dbo.split(col1,';') splittedValues
group by splittedValues.items

DEMO in Sql fiddle

答案 3 :(得分:0)

首先创建一个函数,将逗号或任何其他运算符(;)分隔的字符串放入一个表中,并使用该临时表,在该表上应用GROUP函数。

所以你会得到单独的价值。

“选择d.number,count(*)from(从dbo.CommaseparedListToTable中选择数字('Hundley; Edward; Ana; Isler; Hunsberger; Hunsberger; Hundley',';'))d 按d.number分组“

答案 4 :(得分:0)

  
    declare @text nvarchar(255) = 'Edward; Hundley; AnaIsler; Hunsberger; Hunsberger; Hundley ';
    declare @table table(id int identity,name varchar(50));

    while @text like '%;%'
    Begin
    insert into @table (name)
    select SUBSTRING(@text,1,charindex(';',@text)-1)
    set @text = SUBSTRING(@text, charindex(';',@text)+1,LEN(@text))
    end 
    insert into @table (name)
    select @text
    select name , count(name ) counts from @table group by name

<强>输出

name      count 
AnaIsler    1
Hundley     2
Hunsberger  2
Edward      1