根据列值从表中删除重复的行

时间:2013-01-10 10:56:17

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

我有一张表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行。

4 个答案:

答案 0 :(得分:1)

您可以使用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 |

答案 1 :(得分: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 :(得分:0)

你也可以使用这样的连接:

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 |

答案 3 :(得分:0)

我喜欢使用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