我有一个返回客户及其地址列表的查询。
ID FName LName Address1 City Postcode
--------------------------------------------------------
1 James Smith 1 Bank Street London W1C 1AA
2 Sarah Jones 45 Moor Ave London SW1 1YH
3 Mary Smith 1 Bank Street London W1C 1AA
4 Sean Baker 17 White Blvd London SE3 7TH
5 Bob Patel 58B Canal St London NW2 2TT
6 Seeta Patel 58B Canal St London NW2 2TT
7 David Hound 4 Main St London E11 8AB
我正在尝试从此数据中生成另一个查询,该查询选择相关/共同生活的客户列表。此标准将与地址1和邮政编码字段相同。
我的问题是如何生成一个查询,该查询只选择至少有一条匹配[Address1]和[Postcode]的其他记录的记录?即;在上面的示例中,仅返回记录1,3,5和6.
答案 0 :(得分:3)
Select * From
Customers c JOIN
(SELECT Address1, PostCode FROM Customer GROUP BY Address1, PostCode HAVING Count(1) > 1) c2
ON c.Address1 = c2.Address1 AND c.PostCode = c2.PostCode