我具有以下结构
+----+----+
| C1 | C2 |
+---------+
| 1 | A |
| 2 | A |
| 3 | A |
| 4 | B |
| 5 | B |
| 6 | A |
| 7 | C |
+----+----+
输出应为
C1 C2
3 A
5 B
6 A
7 C
它应该在每个具有相同C2值的序列中返回最高C1值
简单的小组无法正常工作,请指导如何实现。
预先感谢
答案 0 :(得分:3)
答案 1 :(得分:2)
您可以通过在表中具有不同LEFT JOIN
值的下一个值上C2
将表自身对齐来完成此操作。我们使用GROUP BY
来获取表中没有匹配项的最后一行:
SELECT MAX(d1.C1) AS C1, MAX(d1.C2) AS C2
FROM data d1
LEFT JOIN data d2 ON d2.C2 != d1.C2
AND d2.C1 = (SELECT MIN(C1) FROM data d3 WHERE d3.C1 > d1.C1)
GROUP BY d2.C1
ORDER BY C1
输出:
C1 C2
3 A
5 B
6 A
7 C
答案 2 :(得分:2)
您想要每个c2系列的最大c1:
select t.* from tablename t
where
coalesce(
(select c2 from tablename where c1 = (
select min(c1) from tablename where c1 > t.c1)
), ''
) <> t.c2
请参见demo。
结果:
| C1 | C2 |
| --- | --- |
| 3 | A |
| 5 | B |
| 6 | A |
| 7 | C |