Question

Table Pattern has single column with the following values:

NewsletteridPattern
------------
%50%
%51%

Table B has the following values:

SubscriberId NewsletterIdCsv
------------ -----------------
47421584     51
45551047     50,51
925606902    50
47775985     51    

I have the following query which basically counts the comma seperated values by using the pattern:

SELECT *
FROM TABLEB t WITH (nolock)
JOIN Patterns p ON (t.NewsletteridPattern LIKE p.pattern)

The problem is that the count is incorrect as for example my pattern has %50% and %51% and thus the row number 2 from Table B should be counted twice, however with my query it is only once, how do I fx that?

EDIT :
I forgot to add DISTINCT in my original query which was causing the issue:

SELECT Count(Distinct Subscriberid)
FROM TABLEB t WITH (nolock)
JOIN Patterns p ON (t.NewsletteridPattern LIKE p.pattern)
Was it helpful?

Solution

I mocked up your data as such:

create table #pattern (pattern varchar(50))

insert into #pattern values ('%50%')
insert into #pattern values ('%51%')

create table #subscriber (id varchar(50), newsletter varchar(50))

insert into #subscriber values ('47421584', '51')
insert into #subscriber values ('45551047', '50,51')
insert into #subscriber values ('925606902', '50')
insert into #subscriber values ('47775985', '51')

SELECT pattern, COUNT(*) AS Counter
FROM #subscriber t WITH (nolock)
    JOIN #pattern p ON (t.newsletter LIKE p.pattern)
GROUP BY pattern

And my select statement returns:

pattern  Counter
-------  -------
%50%        2

%51%        3

What is your final goal? Are you just concerned about counting the number of rows by pattern or are you trying to do a select of rows by pattern?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top