编写一个 SQL 查询,为每个 ID 选择最小的客户值。将该数据集连接回原始表,其中原始表的 Customer 值大于每个相应 ID 的最小值。这是一个 SQLFiddle 示例:
http://www.sqlfiddle.com/#!9/93296f/20
这是用于重新创建您的问题的 DDL:
CREATE TABLE Table1
(`Id` int, `Customer_Account` int, `City` varchar(9));
INSERT INTO Table1
(`Id`, `Customer_Account`, `City`)
VALUES
(1, 123, 'London'),
(1, 123, 'Paris'),
(1, 456, 'Paris'),
(1, 456, 'Mumbai'),
(1, 123, 'Mumbai'),
(1, 789, 'Singapore');
这是用于显示重复客户帐户的 DML。查询 3 应该会为您提供最终结果。
-- Query 1: Find the First Account for each Customer
select `Id`,
min(`Customer_Account`) as 'First Account by Customer'
from Table1 group by `Id`;
-- Query 2: Find the First Account for Each Customer by City
select `Id`,
min(`Customer_Account`) as 'First Account by City',
`City`
from Table1
group by `Id`, `City`;
-- Query 3: Find the Duplicate Customer Accounts by ID
select distinct
A.Id,
A.Customer_Account as 'Duplicate Account by Customer',
FirstAcctList.First_Account
from Table1 A
join (
select
`Id`,
min(`Customer_Account`) as 'First_Account'
from Table1 group by `Id`) as FirstAcctList
on FirstAcctList.First_Account <> A.Customer_Account;