Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有保证数据集的Mysql分组_Mysql_Group By_Distinct_Having - Fatal编程技术网

具有保证数据集的Mysql分组

具有保证数据集的Mysql分组,mysql,group-by,distinct,having,Mysql,Group By,Distinct,Having,你好, 我得到了下表: +----+----+-------+----------+ | p1 | p2 | value | position | +----+----+-------+----------+ | 1 | 5 | 0 | 1 | | 1 | 6 | 0 | 2 | | 1 | 7 | 0 | 3 | | 1 | 7 | 1 | 4 | | 1 | 8 | 1 |

你好, 我得到了下表:

+----+----+-------+----------+
| p1 | p2 | value | position |
+----+----+-------+----------+
|  1 |  5 |     0 |        1 |
|  1 |  6 |     0 |        2 |
|  1 |  7 |     0 |        3 |
|  1 |  7 |     1 |        4 |
|  1 |  8 |     1 |        5 |
+----+----+-------+----------+
作为需要查询的结果,确切地说,此结果:

+----+----+-------+----------+
| p1 | p2 | value | position |
+----+----+-------+----------+
|  1 |  5 |     0 |        1 |
|  1 |  6 |     0 |        2 |
|  1 |  7 |     1 |        4 |
|  1 |  8 |     1 |        5 |
+----+----+-------+----------+
正如您将注意到的,必须对具有相同p1和p2组合的数据集进行分组,但我需要具有最高位置值的数据集。这种行为必须得到保证

我试过这样的方法:

SELECT *
FROM table
GROUP BY p1, p2
HAVING MAX(position)
没有适当的结果。 有人有主意吗


有几种方法可以做到这一点。下面是一个在子查询中使用聚合的选项:

select t.*
from yourtable t
   join (select p1, p2, max(position) maxposition
         from yourtable
         group by p1, p2) t2 on t.p1 = t2.p1 
                            and t.p2 = t2.p2
                            and t.position = t2.maxposition

这将很好

与Alex的问题相比,措辞巧妙的问题可能在解释上。取决于实际的模式。@Drew-是的,有很多不同的方法可以做到这一点。在我看来,其他数据库使它变得容易多了。Alex的修订答案肯定也会起作用,而且应该比不存在的答案更有效。这是子查询优化的问题是的,t2,可能是派生的。看见
select t.*
from yourtable t
   join (select p1, p2, max(position) maxposition
         from yourtable
         group by p1, p2) t2 on t.p1 = t2.p1 
                            and t.p2 = t2.p2
                            and t.position = t2.maxposition
SELECT RESULT.* 
         FROM resultset RESULT 
              INNER JOIN 
              (SELECT p1,p2,value,(MAX(position)) AS position
               FROM resultset GROUP BY p1, p2) AS T2
              ON RESULT.p1=T2.p1 AND RESULT.p2= T2.p2 AND RESULT.position=T2.position