SQL:如何在多个列上选择一个表的公用行

SQL:如何在多个列上选择一个表的公用行,sql,sql-server,sql-server-2000,rows,Sql,Sql Server,Sql Server 2000,Rows,我有一张桌子: 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

我有一张桌子:

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
下面是我开始编写的表和查询的列表

所有行上页面的公共值 我希望从这个表中提取每个列pro的公共列页面。 以下是我们的期望:

 1
 9
  2
  3
  4
  5
 12
 13
 14
 15
我尝试使用:

SELECT DISTINCT a.page
FROM a
WHERE a.page IN (
  SELECT b.page FROM a as b
  WHERE b.pro <> a.pro
) 
相反的查询至少有一个不同的值,但不是所有的时间

我希望提取链接到一个或多个pro的页面,但不是所有pro都通用的,这与前面的查询完全相反

以下是我们的期望:

 1
 9
  2
  3
  4
  5
 12
 13
 14
 15
我无法找到这两个问题的解决方案:' 有人能帮我做那些吗

致意


编辑:SQLFIDLE url对于问题的第一部分,请尝试以下查询:

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)
第二个查询是所有页面值的简单减法:

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)

只需要一点反向思考——逐页分组,并为每个页面计算不同的pro值。返回与不同pro值的总和匹配的行


编辑:对于第二个问题,只需将=替换为“Exception关键字在SQL server 2000上不起作用,但我看到了其中的逻辑。很抱歉,在Fiddle上尝试了,它起了作用,所以我建议它在目标DB上工作:没问题,我已成功地将其更改为sql server 2000,如下所示:从不存在的as t4中选择DISTINCT t4.page从as t1中选择DISTINCT t1.page从as t2中选择COUNTDISTINCT t2.pro从as t2中选择t2.page=t1.page=从as t1中选择COUNTDISTINCT t3.pro如t3和t4.page=t1.page和t1.pro=t4.pro所示,请参见