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

久未见 提交于 2019-12-06 11:54:47

问题


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


回答1:


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




回答2:


Fot the first part of the question, try this query:

SELECT DISTINCT t1.page FROM a t1
WHERE (SELECT COUNT(DISTINCT t2.pro) FROM a t2 WHERE
       t2.page = t1.page) = 
(SELECT COUNT(DISTINCT t3.pro) FROM a t3)

And the second query is the simple substraction from all page values:

SELECT DISTINCT t4.page FROM a t4
EXCEPT
SELECT DISTINCT t1.page FROM a t1
WHERE (SELECT COUNT(DISTINCT t2.pro) FROM a t2 WHERE
       t2.page = t1.page) = 
(SELECT COUNT(DISTINCT t3.pro) FROM a t3)


来源:https://stackoverflow.com/questions/17469739/sql-how-to-select-common-lines-of-one-table-on-several-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!