HIHO, 我得到了下表:
+----+----+-------+----------+
| 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)
没有正确的结果。 有没有人有想法?
答案 0 :(得分:1)
http://sqlfiddle.com/#!9/499b3/3
SELECT t.*
FROM `table` t
LEFT JOIN `table` t1
ON t.p1 = t1.p1
AND t.p2 = t1.p2
AND t.position<t1.position
WHERE t1.p1 IS NULL
答案 1 :(得分:0)
有几种方法可以做到这一点。这是在子查询中使用聚合的一个选项:
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
答案 2 :(得分:0)
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
这样可以正常使用