1

我遇到了一个问题,到目前为止我找不到答案。

我有一张这样的桌子:

column1 | column2 | column3
---------------------------
name1   | 3       | 12
name1   | 3       | 10
name1   | 2       | 17
name2   | 3       | 15
name2   | 3       | 15
name2   | 2       | 11

如何删除在column2和 column3 中没有最高值的行,(Column2具有优先级)?

结果应如下所示:

column1 | column2 | column3
---------------------------
name1   | 3       | 12
name2   | 3       | 15
name2   | 3       | 15
4

2 回答 2

0

您可以使用这样的查询:

DELETE FROM yourtable
WHERE
  (column1, column2, column3) NOT IN (
    SELECT * FROM (
      SELECT yourtable.column1, yourtable.column2, max(column3) max_column3
      FROM
        yourtable INNER JOIN (
          SELECT   column1, max(column2) max_column2
          FROM     yourtable
          GROUP BY column1) mx
        ON yourtable.column1=mx.column1
           AND yourtable.column2=mx.max_column2
      GROUP BY
        yourtable.column1) s
  )

在此处查看小提琴。

于 2013-02-21T18:29:11.450 回答
0

删除会让人感到困惑,但这些是您要保留的行:

SELECT 
    a.col1, a.col2, b.col3 
FROM
    (select col1, max(col2) as col2 from table1 group by col1) as a INNER JOIN
    (select col1, col2, max(col3) as col3 from table1 group by col1, col2) as b 
    ON 
        a.col1 = b.col1 AND a.col2 = b.col2;

如@fthiella 所述,您可以简单地删除不在此查询中的行。

看到这个链接

于 2013-02-21T18:32:32.893 回答