如何使用子查询从count语句列出?

时间:2017-09-28 07:59:38

标签: sql count subquery sql-server-2014 exists

我们在TOTEMP表中有一些员工有重复的CIVILID,现在我想从EMP表中找到他们的名字

我尝试了以下查询

SELECT P.FIRSTNAME,ID
FROM EMP p
where  exists (SELECT CIVILID, COUNT (CIVILID)
               FROM TOTEMP AS D
               group by CIVILID
               HAVING (COUNT (CIVILID) >1) ) 
  

选择EMP表中的所有记录

2)我尝试了一个IN语句

SELECT P.FIRSTNAME,p.ID
FROM EMP p ,UDFEMP  k
where  p.ID in (SELECT CIVILID ,COUNT (CIVILID)
                FROM TOTEMP AS D
                group by CIVILID
                HAVING (COUNT (CIVILID) >1) ) 
  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

此致

enter image description here

2 个答案:

答案 0 :(得分:1)

SELECT p.FIRSTNAME,p.ID,d.CIVILID
    FROM EMP p inner join TOTEMP d
    on p.id = d.id
    where  d.CIVILID in (select CIVILID from TOTEMP
                        group by CIVILID having count(ID)>1 );

希望它有所帮助!

答案 1 :(得分:0)

这可以通过existsin运算符完成,但您的查询都有问题。

exists变体缺少pd之间的关系:

SELECT p.firstname, p.id
FROM   emp p
WHERE  EXISTS (SELECT   *
               FROM     totemp d
               WHERE    p.id = d.civilid -- Here!
               GROUP BY civilid
               HAVING   COUNT(civilid) > 1)

in变体只需在内部查询中选择id,而不是多列(并且不需要与udfemp交叉加入):

SELECT p.firstname, p.id
FROM   emp p
where  p.id in (SELECT   civilid
                FROM     totemp
                GROUP BY civilid
                HAVING   COUNT(civilid) > 1)