从多个表(从三个表)中选择ID的数量

时间:2019-05-14 20:55:20

标签: sql sql-server tsql

我需要这个数:

select distinct ID
from (
    select ID from A 
    union all
    select ID from B 
    union all
    select ID from C 
) ids
GROUP BY ID HAVING COUNT(*) > 1;

但是我不知道该怎么做。

2 个答案:

答案 0 :(得分:1)

使用子查询:

select count(*)
from (select ID
      from (select ID from A 
            union all
            select ID from B 
            union all
            select ID from C 
           ) ids
      group by ID
      having count(*) > 1
     ) i;

SELECT DISTINCT几乎不需要GROUP BY,在这种情况下绝对不需要。

答案 1 :(得分:0)

您只想查找在A,B,C表中再出现2次的ID,SQL如下:

select count(1) from (
select
    id,
    count(1)
from
    (
    select ID from A 
    union all
    select ID from B 
    union all
    select ID from C 
   ) 
group by id having(count(1)>1)
) tmp