gpt4 book ai didi

SQL : Using GROUP BY and MAX on multiple columns

转载 作者:IT王子 更新时间:2023-10-28 23:50:01 25 4
gpt4 key购买 nike

我有一个 SQL 查询问题。让我们以这个示例数据为例

itemID  catID  attrib1  attrib2
1 1 10 5
2 1 10 7
3 1 5 10
4 2 18 15

我想返回每个类别的最佳项目(attrib1 优先于 attrib2)

显然,SELECT catID, MAX(attrib1), MAX(attrib2) FROM test_table GROUP BY catID 不起作用,因为它将为第一只猫返回 10 和 10。

那么有没有办法告诉 MySQL 从 attrib2 行中选择最大值,但只考虑 attrib1 也是最大值的行?即返回以下数据

 catID  attrib1  attrib2
1 10 7
2 18 15

最佳答案

您可以获得最佳的 attrib1 值,然后加入 attrib2 值并获得每个 attrib1 值的最佳值:

select t2.catID, t2.attrib1, max(t2.attrib2)
from
(
select catID, max(attrib1) as attrib1
from test_table
group by catID
) t1
inner join test_table t2 on t2.catID = t1.catID and t2.attrib1 = t1.attrib1
group by t2.catID, t2.attrib1

关于SQL : Using GROUP BY and MAX on multiple columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4045609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com