Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 grouping rows by csv column TSQL

Author  Topic 

sparrow37
Posting Yak Master

148 Posts

Posted - 2013-08-24 : 03:38:57


I have a table with following sample data:

**CategoriesIDs RegistrantID**
47 1
276|275|278|274|277 4
276|275|278|274|277 16261
NULL 16262
NULL 16264
NULL 16265
NULL 16266
NULL 16267
NULL 16268
NULL 16269
NULL 16270
276|275|278 16276
276|275|278|274|277 16292
276|275|278|274|277 16293
276|275|278|274|277 16294
276|275|278|274|277 16295
276|275|278|274|277 16302
276|275|278|274|277 16303
276|275|278|274|277 16304
276|275|278|274|277 16305
276|275|278|274|277 16306
276|275|278|274|277 16307

I need to know :

1). which category has how many regisrtantids (like 277 has how many registrantids) 2). group the registrants by category so that i can find which registrants are in category 277 for example)

Do I need to create a function which generates a table from csv ? I have created a function but not sure if it will work in this situation with IN clause.

Please suggest

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2013-08-24 : 05:42:15
Maybe this can be used:

declare @yourtable table (categoriesids varchar(255),registrantid int);

insert into @yourtable
values ('47',1)
,('276|275|278|274|277',4)
,('276|275|278|274|277',16261)
,(NULL,16262)
,(NULL,16264)
,(NULL,16265)
,(NULL,16266)
,(NULL,16267)
,(NULL,16268)
,(NULL,16269)
,(NULL,16270)
,('276|275|278',16276)
,('276|275|278|274|277',16292)
,('276|275|278|274|277',16293)
,('276|275|278|274|277',16294)
,('276|275|278|274|277',16295)
,('276|275|278|274|277',16302)
,('276|275|278|274|277',16303)
,('276|275|278|274|277',16304)
,('276|275|278|274|277',16305)
,('276|275|278|274|277',16306)
,('276|275|278|274|277',16307)
;
with cte (registrantid,categoriesids,s,e)
as (select registrantid
,isnull(categoriesids,'')+'|' as categoriesids
,1 as s
,charindex('|',isnull(categoriesids,'')+'|',1) as e
from @yourtable
union all
select registrantid
,categoriesids as categoriesids
,e+1 as s
,charindex('|',categoriesids,e+1) as e
from cte
where e<len(categoriesids)
)
select substring(categoriesids,s,e-s)
,count(*)
from cte
group by substring(categoriesids,s,e-s)
;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-24 : 10:44:34
see

http://visakhm.blogspot.in/2010/02/parsing-delimited-string.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -