How can I get the number of occurrences in a SQL IN clause?
05:58 28 Aug 2008

Let's say I have four tables: PAGE, USER, TAG, and PAGE-TAG:

Table      | Fields
------------------------------------------
PAGE       | ID, CONTENT
TAG        | ID, NAME
USER       | ID, NAME    
PAGE-TAG   | ID, PAGE-ID, TAG-ID, USER-ID

And let's say I have four pages:

PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 
PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1  
PAGE#3 'Content page 3' tagged with tag#7 by user#1
PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1

I expect my query to look something like this:

select page.content ?
from page, page-tag 
where 
page.id = page-tag.pag-id 
and page-tag.tag-id in (1, 3, 8) 
order by ? desc

I would like to get output like this:

Content page 2, 3
Content page 4, 2
Content page 1, 1

Quoting Neall

Your question is a bit confusing. Do you want to get the number of times each page has been tagged?

No

The number of times each page has gotten each tag?

No

The number of unique users that have tagged a page?

No

The number of unique users that have tagged each page with each tag?

No

I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear.

SQL IN works like a boolean operator OR. If a page was tagged with any value within the IN clause then it returns true. I would like to know how many of the values inside of the IN clause return true.

Below I show, the output I expect:

page 1 | in (1,2)   -> 1

page 1 | in (1,2,3) -> 1

page 1 | in (1)     -> 1

page 1 | in (1,3,8) -> 1

page 2 | in (1,2)   -> 1

page 2 | in (1,2,3) -> 2

page 2 | in (1)     -> 1

page 2 | in (1,3,8) -> 3

page 4 | in (1,2,3) -> 1

page 4 | in (1,2,3) -> 1

page 4 | in (1)     -> 1

page 4 | in (1,3,8) -> 2

This will be the content of the page-tag table I mentioned before:

   id       page-id  tag-id  user-id  
    
    1       1        1       1 
    
    2       1        1       2 
    
    3       2        3       2 
    
    4       2        1       2 
    
    5       2        8       1 
    
    6       3        7       1 
    
    7       4        1       1 
    
    8       4        8       1 

@Kristof does not exactly what I am searching for but thanks anyway.

@Daren If I execute your code I get the next error:

#1054 - Unknown column 'page-tag.tag-id' in 'having clause'

@Eduardo Molteni Your answer does not give the output in the question but:

Content page 2 8
Content page 4 8
content page 2 3
content page 1 1
content page 1 1
content page 2 1
cotnent page 4 1

@Keith I am using plain SQL not T-SQL and I am not familiar with T-SQL, so I do not know how your query translate to plain SQL.

Any more ideas?

sql