当前SQL:
select t1.*
from table t1
where t1.id in ('2', '3', '4')
目前的结果:
id | seq
---+----
3 | 5
2 | 7
2 | 5
3 | 7
4 | 3
尝试选择最大值:
select t1.*
from table t1
where t1.id in ('2', '3', '4')
and t1.seq = (select max(t2.seq)
from table2 t2
where t2.id = t1.id)
由于我使用in
列表,这显然不起作用。如何调整我的SQL以获得这些预期结果:
id | seq
---+----
2 | 7
3 | 7
4 | 3
答案 0 :(得分:5)
Group By是你的朋友:
SELECT
id,
MAX(seq) seq
FROM TABLE
GROUP BY id
编辑:对评论的回应。要从匹配max seq和id的表中获取其余数据,只需加入表:
SELECT t1.*
FROM TABLE t1
INNER JOIN (
SELECT
id
MAX(seq) as seq
FROM TABLE
GROUP BY id
) as t2
on t1.id = t2.id
and t1.seq = t2.seq
编辑:Gordon和Jean-Francois是正确的你也可以使用ROW_NUMBER()分析函数来获得相同的结果。您需要检查应用程序的性能差异(我没有检查)。这是一个例子:
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (
PARTITION BY id
ORDER BY seq DESC) as row_num
,*
FROM TABLE
) as TMP
WHERE row_num = 1
答案 1 :(得分:0)
此SQL查询将为您提供来自个人ID的最大序列号。
SELECT t1.*
FROM t1
WHERE t1.id in ('2', '3', '4')
AND NOT EXISTS (
SELECT *
FROM t1 t2
WHERE t2.id = t1.id
AND t2.seq > t1.seq
答案 2 :(得分:0)
select *
from table
where (id,seq) in
(
select id,max(seq)
from table
group by id
having id in ('2','3','4')
);
即如果id
和/或seq
完全属于该表的PK。
答案 3 :(得分:0)
这是另一个例子,使用我在前面评论中提到的第一个/最后一个方法:
with sd as (select 3 id, 5 seq, 1 dummy from dual union all
select 2 id, 7 seq, 2 dummy from dual union all
select 2 id, 5 seq, 3 dummy from dual union all
select 3 id, 7 seq, 4 dummy from dual union all
select 3 id, 7 seq, 5 dummy from dual union all
select 4 id, 3 seq, 6 dummy from dual)
select id,
max(seq) max_seq,
max(dummy) keep (dense_rank first order by seq desc) max_rows_dummy
from sd
group by id;
ID MAX_SEQ MAX_ROWS_DUMMY
---------- ---------- --------------
2 7 2
3 7 5
4 3 6
keep (dense_rank first order by ...)
位请求在行的顺序列表中保持与等级1相关联的值。如果多于一行的等级为1,则max(...)
位存在;它只是打破关系的一种方式。