代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

SQL:如何选择具有重复项的唯一行

  •  3
  • Zachary Scott  · 技术社区  · 14 年前

    我们的客户向我们提供重复项目的合同。我们为独特的产品做广告。在不进行许多子查询的情况下,如何选择一组具有描述的UPC?可怕的例子:

    /* 
    eventID     int
    groupID     int            // This field is different between fields
    upc_ean     numeric(18,0)
    description varchar(512)   // Description is slightly different but same info
    size        varchar(512)   // Size is slightly different but same info
    */
    
    select A.eventid, A.upc_ean,
    
           ( select top 1 description 
             from myTable B 
             where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as description,
    
           ( select top 1 size
             from myTable B
             where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as size
    
    from ( select distinct eventid, upc_ean from myTable) A
    

    在没有子查询的情况下,有没有任何方法可以做同样的事情,以某种方式将这两个查询连接在一起,而不使用eventid和upc-ean作为pk来繁殖记录或显示重复项?

    2 回复  |  直到 14 年前
        1
  •  5
  •   OMG Ponies    14 年前

    如有必要,您可以向以下部分添加ORDER BY子句。

    使用热膨胀系数:

    WITH example AS (
      SELECT a.eventid, 
             a.upc_ean,
             a.description,
             a.size,
             ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
        FROM YOUR_TABLE a)
    SELECT x.eventid,
           x.upc_ean,
           x.description, 
           x.size
      FROM example x
     WHERE x.rank = 1
    

    不带CTE:

    SELECT x.eventid,
           x.upc_ean,
           x.description, 
           x.size
      FROM (SELECT a.eventid, 
                   a.upc_ean,
                   a.description,
                   a.size,
                   ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
              FROM YOUR_TABLE a) x
     WHERE x.rank = 1
    
        2
  •  5
  •   bobs    14 年前

    您可以这样做:

    SELECT A.eventid, A.upc_ean, MAX(description) as description, MAX(size) as size
    FROM myTable
    GROUP BY eventid, upc_ean
    

    你应该得到类似的结果。