3

我有这个 SQL:

SELECT itemId, parentId, value FROM item ORDER BY value DESC

正确返回:

+--------+------------------+
| itemId | parentId | value |
+--------+------------------+
|      1 |        5 |   500 |
|      4 |        1 |   500 |
|      2 |        5 |    10 |
|      5 |        1 |    10 |
|      3 |        5 |     0 |
|      6 |        1 |     0 |
+--------+----------+-------+

我尝试添加“GROUP BY parentId”,但这似乎选择了两个随机项目,忽略了 ORDER BY 子句:

+--------+------------------+
| itemId | parentId | value |
+--------+------------------+
|      2 |        5 |    10 |
|      6 |        1 |     0 |
+--------+----------+-------+

我应该使用什么 SQL 来仅返回每个 parentId 具有最高值的项目?:

+--------+------------------+
| itemId | parentId | value |
+--------+------------------+
|      1 |        5 |   500 |
|      4 |        1 |   500 |
+--------+----------+-------+
4

1 回答 1

1

对于 each ,只有当它是它的itemId时才选择它:valueMAXparentId

SELECT itemId, parentId, value
FROM item i
WHERE value = (SELECT MAX(value) 
               FROM item t 
               WHERE t.parentId = i.parentId)

返回:

| ITEMID | PARENTID | VALUE |
-----------------------------
|      1 |        5 |   500 |
|      4 |        1 |   500 |

演示

于 2012-09-23T17:11:19.243 回答