代码之家  ›  专栏  ›  技术社区  ›  andraiamatrix

SQL查询:标识重复的值,并在不重复的列中显示值

  •  1
  • andraiamatrix  · 技术社区  · 6 年前

    我在Hadoop中有我正在分析的数据。有一些重复的条目,其中A、B列是重复的,C列是不同的。我要做的是只标识A、B重复项,然后打印出C列中每个重复项的不同值。

    样本数据:

    row,  data, input_date, INPUT__FILE__NAME
      0, data1,   20180702,         LOCATION1
      1, data1,   20180702,         LOCATION2
      2, data1,   20180702,         LOCATION2
    
      3, data2,   20180702,         LOCATION1
      4, data2,   20180702,         LOCATION1
      5, data2,   20180702,         LOCATION2
      6, data2,   20180702,         LOCATION3
      7, data2,   20180702,         LOCATION3
    
      8, data3,   20180702,         LOCATION2
    
      9, data4,   20180702,         LOCATION3
    

    (注意 INPUT__FILE__NAME 是Hadoop中数据来自的文件位置的元数据值。如果有关系的话。但据我所知,就SQL查询而言,它可以像另一列一样被处理。

    在这个例子中,我将使用 data input_date 以识别重复项。我想看到 输入文件名 他们中的每一个。

    所需的输出(如果另一个输出有意义,可以更改输出的结构--我只需要 INPUT_FILE_NAME 值):

        data, input_date, INPUT__FILE__NAME
       data1,   20180702,         LOCATION1
       data1,   20180702,         LOCATION2
       data2,   20180702,         LOCATION1
       data2,   20180702,         LOCATION2
       data2,   20180702,         LOCATION3
    

    (所以在输出中,我 不要 需要看 data3 也不 data4 因为它们不会被复制。)

    我发现,要识别副本,我可以执行以下操作:

    SELECT data, input_date, count(DISTINCT INPUT__FILE__NAME)
    FROM table
    GROUP BY data, input_date
    HAVING count(DISTINCT INPUT__FILE__NAME)>1;
    

    但是,我还没有找到一种方法来同时标识具有不同计数的值>1,然后打印出这些不同值(因为标识计数>1需要聚合,但打印不同值需要取消聚合)。是否可以在单个查询中执行?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Gordon Linoff    6 年前

    我倾向于使用窗口功能:

    select distinct data, input_date, input__file__name
    from (select t.*,
                 min(input__file__name) over (partition by data, input_date) as min_ifn,
                 max(input__file__name) over (partition by data, input_date) as max_ifn
          from t
         ) t
    where min_ifn <> max_ifn;
    
        2
  •  0
  •   Yogesh Sharma    6 年前

    你可以使用 union all :

    select distinct t.data, t.input_date, t.INPUT__FILE__NAME
    from table t
    union all
    select distinct t.data, t.input_date, t.INPUT__FILE__NAME
    from table t
    where not exists (select 1 
                      from table t1 
                      where t1.data = t.data and 
                            t1.input_date = t.input_date and
                            t1.INPUT__FILE__NAME <> t.INPUT__FILE__NAME
                     );