选择内部连接与多部分标识符和有子句

时间:2013-03-05 14:12:20

标签: inner-join identifier multipart having-clause

我需要为具有重复项的多部分标识符选择某些字段。

我有查询来获取正确的重复项。

SELECT   b.MemEmpID, b.LastName, b.FirstName
               FROM     table1 As b
               GROUP BY b.MemEmpID, b.LastName, b.FirstName
               HAVING   Count(*) > 1

但是在找到重复项之后,我需要从同一个表中获取更多信息,但仅针对具有重复项的多部分标识符。如下所示。

有人可以用正确的语法帮助我吗?

SELECT a.memempid, a.depkey, a.lastname, a.firstname, a.birthdate, a.memrelation
FROM   table1 As a
INNER JOIN(SELECT   b.MemEmpID, b.LastName, b.FirstName
               FROM     table1 As b
               GROUP BY b.MemEmpID, b.LastName, b.FirstName
               HAVING   Count(*) > 1)
ON b.memempid = a.memempid
AND b.lastname = a.lastname
AND b.firstname = a.firstname

1 个答案:

答案 0 :(得分:2)

你真的很亲密。您需要为子查询添加别名。

table1 As b使用分组()丢失了它的范围,因此您需要为带括号的子查询设置别名。您可以重复使用b - 它只会知道返回的列,但为了清楚起见,我选择了(...) as c来消除歧义。

SELECT a.memempid, a.depkey, a.lastname, a.firstname, a.birthdate, a.memrelation
FROM   table1 As a
INNER JOIN
    (SELECT   b.MemEmpID, b.LastName, b.FirstName
     FROM     table1 As b
     GROUP BY b.MemEmpID, b.LastName, b.FirstName
     HAVING   Count(*) > 1
    ) as c
ON c.memempid = a.memempid
    AND c.lastname = a.lastname
    AND c.firstname = a.firstname