0

我有一张桌子说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

4 回答 4

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

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

| PROMOID | VALUE | PROMOTYPE | NIGHTTYPE |
-------------------------------------------
|     102 |    12 |         a |         b |
|     103 |    17 |         c |         d |
于 2013-01-10T11:02:29.510 回答
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;
于 2013-01-10T11:02:49.427 回答
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;

看到这个 SQLFiddle

结果

| PROMOID | VALUE | PROMOTYPE | NIGHTTYPE |
-------------------------------------------
|     102 |    12 |         a |         b |
|     103 |    17 |         c |         d |
于 2013-01-10T11:05:10.897 回答
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 小提琴在这里

于 2013-01-10T11:24:46.250 回答