【问题标题】:Delete duplicate rows from a table on the basis of column values根据列值从表中删除重复行
【发布时间】:2013-01-10 19:24:46
【问题描述】:

我有一张桌子说PromoDescription

--------------------------------------------------
| PromoId | Value | PromoType  |NightType|
--------------------------------------------------
|   101   |   11  |      a     |     b   |       
|   102   |   12  |      a     |     b   |       
|   103   |   17  |      c     |     d   |       
|   104   |   14  |      c     |     d   |       

上面的表格有 4 列,我已经添加了示例值。

问题:对于PromotionTypeNightType的相同组合,我必须保留折扣的最高值并删除其余行。

对于样本值,应删除第 1 行和第 4 行。

【问题讨论】:

  • 您不必删除行,您可以尝试按促销类型、夜间类型和按价值排序,选择前 1 个,您将获得结果集。通过保留行,您将拥有更改的历史记录。

标签: sql sql-server sql-server-2008


【解决方案1】:

请检查:

with c as
(
    select *, row_number() over(partition by PromotionType, NightType order by [Value] desc) as n
    from PromoDescription
)
delete from c
where n > 1;

【讨论】:

    【解决方案2】:

    您可以使用 CTE 来执行此操作:

    ;with cte as
    (
      select promoid, value, promotype, NightType,
        row_number() over(partition by promotype, NightType order by value desc) rn
      from yourtable
    )
    delete
    from cte
    where rn > 1;
    

    SQL Fiddle with Demo

    这将从表中删除任何没有最大值的内容:

    | PROMOID | VALUE | PROMOTYPE | NIGHTTYPE |
    -------------------------------------------
    |     102 |    12 |         a |         b |
    |     103 |    17 |         c |         d |
    

    【讨论】:

      【解决方案3】:

      你也可以像这样使用join:

      DELETE table1 
        FROM table1
        LEFT JOIN 
        (SELECT MAX(Value) as MaxValue, Promotype, nighttype FROM table1
         GROUP BY Promotype, nighttype
        )A
        ON table1.value = A.MaxValue
        AND table1.Promotype = A.Promotype
        AND table1.nighttype = A.nighttype
        WHERE A.MaxValue IS NULL;
      

      See this SQLFiddle

      结果

      | PROMOID | VALUE | PROMOTYPE | NIGHTTYPE |
      -------------------------------------------
      |     102 |    12 |         a |         b |
      |     103 |    17 |         c |         d |
      

      【讨论】:

        【解决方案4】:

        我喜欢使用NOT EXISTS,但这只是一般主题的变体:

        select *
        from yourtable a
        where not exists
          (
          select 1
          from yourtable b
          where 
              a.PromoType = b.PromoType and
              a.NightType = b.NightType and
              a.Value < b.Value
        
          )
        

        SQL FIDDLE HERE

        【讨论】:

          猜你喜欢
          • 2011-04-21
          • 2019-05-29
          • 2021-06-24
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 2016-03-13
          • 1970-01-01
          相关资源
          最近更新 更多