Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
I would like to add a derived column to my query. I would like to count the number of times a pattern ocurs in a field, for each record produced by the select statement. Pretend this is my tablecol1 col2 col3a b cca d cccand I want to say select "number times c appears in col3 for each record" from tabledesired output isrow1 - 2 occurances of crow2 - 3 occurances of c
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2010-02-19 : 14:03:20
[code]SELECT *, LEN(col3) - LEN(REPLACE(col3,'c','')) AS [occuranceofc] FROM table[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/
blackX
Posting Yak Master
102 Posts
Posted - 2010-02-19 : 14:39:20
that works...almostwhat if 'c' was a string not just a single character?actually what I really need to do is count the number of times the current date appears in a notes field. The notes are timestamped with each call that is made.
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts
Posted - 2010-02-19 : 15:13:41
What's the definition of the notes field?varchar(max)?
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts
Posted - 2010-02-19 : 15:37:57
maybe this?
declare @t table(col1 int,col2 int,Notes varchar(200))insert @tselect 1,2,'20100219-test,20100219-test1,20090218-test3'union all select 1,3,'20100219-test'union all select 1,5,'20100218-test'
SELECT *, datalength(Notes) - datalength(REPLACE(Notes,'20100219',replicate(' ',len('20100219') - 1))) AS [occuranceofc] FROM @t
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2010-02-20 : 00:18:44
quote:Originally posted by blackX that works...almostwhat if 'c' was a string not just a single character?actually what I really need to do is count the number of times the current date appears in a notes field. The notes are timestamped with each call that is made.
what do you mean by that?it works even for a stringsee
SELECT LEN(val)-LEN(REPLACE(val,'c','')) AS [Occuranceofc]FROM (SELECT 'ccclojfeel nsDSZZcc kkxdlkwqcccccbmqxxc' as val)toutput------------------------------Occuranceofc11
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/
blackX
Posting Yak Master
102 Posts
Posted - 2010-02-24 : 15:52:36
Correct, it works for the string but the count is the number of characters replaced not the occurances of the string. So if i had the followingAABBCCDDAABBCC and was searching for the number of occurnces AABB appeared the desired result would be 2. But the code provided would return 4 because the string to search would be 4 characters less in length if we replaced AABB with nothing.