sql查询最大值及其id的方法

2024-12-28 16:16:02
推荐回答(5个)
回答1:

SELECT b.ID, b.ab
FROM (SELECT ID, ab, tt
FROM aaaa
UNION ALL
SELECT ID, ab, tt
FROM bbbb) b
WHERE EXISTS (SELECT 1
FROM (SELECT a.tt, MAX (a.ab) ab
FROM (SELECT ID, ab, tt
FROM aaaa
UNION ALL
SELECT ID, ab, tt
FROM bbbb) a
GROUP BY a.tt) c
WHERE c.tt = b.tt AND c.ab = b.ab)
AND b.tt = '02'

最后一行替换你想查的tt

回答2:

可以用union all连接两个查询,分别查出两种表对应的id和ab的值,然后外层嵌套sql(按ab降序排序,取第一行数据)

回答3:

SELECT id,max(ab) as ab
from
(
select * from AAAA
union
select * from BBBB)
where tt='02'
group by id

回答4:

select case when a.ab>b.ab then a.id else b.id end as id
,case when a.ab>b.ab then a.ab else b.ab end as ab
from aaaa as a inner join bbbb as b on a.tt=b.tt

回答5:

SELECT b.id,b.tt,MAX(ab)as ab
FROM (SELECT ID, ab, tt
FROM aaaa
UNION ALL
SELECT ID, ab, tt
FROM bbbb) b
where tt='02'
group by b.ID,tt