Search code examples
sqlsql-serversql-server-2000rows

SQL: how to select common lines of one table on several column


I have a table :

create table a (page int, pro int)
go
insert into a select 1, 2
insert into a select 4, 2
insert into a select 5, 2
insert into a select 9, 2
insert into a select 1, 3
insert into a select 2, 3
insert into a select 3, 3
insert into a select 4, 3
insert into a select 9, 3
insert into a select 1, 4
insert into a select 9, 4
insert into a select 12, 4
insert into a select 1, 5
insert into a select 9, 5
insert into a select 12, 5
insert into a select 13, 5
insert into a select 14, 5
insert into a select 15, 5
go

(here is the SQLfiddle of this table and queries I began to write )

Common value of page on ALL lines

  1. I'm looking to extract the common column "page" for each column "pro" from this table. here is what we expect :

     1
     9
    

    I tried to use:

    SELECT DISTINCT a.page
    FROM a
    WHERE a.page IN (
      SELECT b.page FROM a as b
      WHERE b.pro <> a.pro
    ) 
    

    but this query returns every "page" that have at least one common values which is not what we need to have. see below :

     1
     4
     9
    12
    

    The opposite query aka different value at least one but not all time

  2. I'm looking to extract the "page" linked to one or more "pro" but without being common to all of them (it's the exact opposite of the previous query)

Here is what we expect :

  2
  3
  4
  5
 12
 13
 14
 15

I can't manage to find a solution to those 2 queries :'( Could anyone help me on those ones?

Best regards

edit: the SQLfiddle url


Solution

  • Just a bit of reversed thinking - group by page and count distinct pro values for each. Return rows that matches the total of distinct pro values

    SELECT [page]
    FROM a
    GROUP BY [page]
    HAVING COUNT(DISTINCT pro) = (SELECT COUNT(DISTINCT pro) FROM a)
    

    SQLFiddle

    EDIT: for the second problem, just replace = with '<' in the final line -> SQLFiddle