SQL:在多列上使用GROUP BY和MAX

编程入门 行业动态 更新时间:2024-10-26 18:30:22
本文介绍了SQL:在多列上使用GROUP BY和MAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用SQL查询时遇到问题.让我们以这个示例数据为例

I have an issue with an SQL Query. Lets take this example data

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

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

I want to return the best item for each category (with attrib1 having priority over attrib2)

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

Obviously, SELECT catID, MAX(attrib1), MAX(attrib2) FROM test_table GROUP BY catID doesn't work since it will return 10 & 10 for the 1st cat.

所以有什么办法告诉MySQL从attrib2行中选择最大值,而仅考虑attrib1也是最大值的情况吗?即返回以下数据

So is there anyway to tell MySQL to select max value from attrib2 row but only consider the ones where attrib1 is also max value ? i.e return the following data

catID attrib1 attrib2 1 10 7 2 18 15

推荐答案

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

You can get the best attrib1 values, and then join in the attrib2 values and get the best of those for each attrib1 value:

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:在多列上使用GROUP BY和MAX

本文发布于:2023-10-20 01:09:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509381.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多列上   SQL   MAX   GROUP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!