【问题标题】:Finding some same values within each ID在每个 ID 中查找一些相同的值
【发布时间】:2019-03-15 12:11:12
【问题描述】:

我有这种数据,ID 列标识了潜在的重复项, 在这个数据中,相同的 ID 表示它是同一个客户,我想要做的是显示不需要 456 帐户,因为它包含在帐户 123 下,有没有办法在 SQL 或 tableau 上做到这一点?我想在 ID 组中显示所有帐户,例如 456。

【问题讨论】:

  • 你用的是什么数据库?
  • 数据来自HANA,但我可以在提取后使用任何工具来解决问题。

标签: sql merge duplicates tableau-api


【解决方案1】:
with cte as (
select min(customer_account) as account, id --This query will get the first account for each ID
from table
group by ID
 )
select customer_account, id --this will show, for each id, all the 'duplicated' customers
from table 
where customer_account not in (select account from cte)

结果应该是:

456 1
789 1

只有一个客户 ID 的 ID 不会出现

【讨论】:

    【解决方案2】:

    编写一个 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;
    

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多