如何选择每种类型中最大的行

jtjikinw  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(449)

我有一个带有pk(“object”,“type”,“mid”)的表,结构如下:

+-----+----------+-------+---------+-----+
| type|  object  | value | preview | mid |
+-----+----------+-------+---------+-----+
| t1  | uid-0001 |   2   | p1      | 1   |
| t1  | uid-0002 |   10  | p2      | 1   |
| t2  | uid-0001 |   1   | p1      | 1   |
| t2  | uid-0003 |   5   | p3      | 1   |
| t3  | uid-0005 |   10  | p5      | 2   |
| t3  | uid-0001 |   40  | p1      | 2   |
| t4  | uid-0004 |   5   | p4      | 2   |
+-----+----------+-------+---------+-----+

我想达到的结果是:

+-----+----------+-------+---------+-----+
| type|  object  | value | preview | mid |
+-----+----------+-------+---------+-----+
| t1  | uid-0002 |   10  | p2      | 1   |
| t2  | uid-0003 |   5   | p3      | 1   |
| t3  | uid-0001 |   40  | p1      | 2   |
| t4  | uid-0004 |   5   | p4      | 2   |
+-----+----------+-------+---------+-----+

我尝试的sql是:

SELECT * 
FROM table 
WHERE value in (SELECT max(value) FROM table GROUP BY type) 
GROUP BY type

但这失败了,因为当表中有多个相同的值时,它得到的值不正确。
我也试过了

SELECT * 
FROM (SELECT * FROM table ORDER BY value desc) x 
GROUP BY type;

但它也有同样的错误。
错误结果示例:

+-----+----------+-------+---------+-----+
| type|  object  | value | preview | mid |
+-----+----------+-------+---------+-----+
| t1  | uid-0002 |   10  | p2      | 1   |
| t2  | uid-0003 |   5   | p3      | 1   |
| t3  | uid-0005 |   10  | p5      | 2   |
| t4  | uid-0004 |   5   | p4      | 2   |
+-----+----------+-------+---------+-----+

在本例中,行 t3 以及 t1 使用相同的值(10,必须用于t1)并在两种类型(t1、t3)中选择它;

sxissh06

sxissh061#

您可以创建一个仅包含每个类型的类型和最大值的表,然后将该表用作筛选器,以仅查看具有最大值的记录

SELECT *
FROM table t
JOIN (
    SELECT
        type
        ,MAX(value) as max_value
    FROM table
    ) m on t.type = m.type and t.value = m.max_value
jhkqcmku

jhkqcmku2#

您的第一次尝试非常接近,您只需要在子查询中添加where子句,将其链接到外部查询,而不是使用 GROUP BY ,以下将得到您想要的结果:

SELECT t.Type, t.Object, t.Value, t.Preview 
FROM Table AS t
WHERE value IN (SELECT max(value) FROM Table AS t2 WHERE t2.Type = t.Type) 
ORDER BY t.Type;

sql fiddle示例
如果您使用的是较新版本的mysql(8.0),那么也可以使用 ROW_NUMBER() :

SELECT t.Type, t.Object, t.Value, t.Preview
FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY Type ORDER BY Value DESC) AS rowNumber
      FROM Table) AS t
WHERE t.RowNumber = 1
ORDER BY t.Type;

db<>fiddle示例

gmxoilav

gmxoilav3#

您可以使用下面的查询来获得最佳解决方案,并确保“value”列的数据类型应为“number”。

SELECT * FROM table WHERE (type,VALUE) IN (SELECT type,MAX(value) FROM table GROUP BY type)

相关问题