SQL 两个表连接后 取最大值问题

来源:百度知道 编辑:UC知道 时间:2024/05/26 07:13:18
A表有一列KS,B表有一列KS,两表连接字段为id,a.id=b.id,请问怎样取id=1的KS最大值和最小值,无论最大KS为A表还是B表。

select
a.id as 'ID',
case when a.ks>b.ks then a.ks else b.ks end as '最大值'
from a,b
where a.id=b.id

select max(KS),min(KS) from (select id,KS from a union select id,KS from b) where id=1;

selsect max(A.KS),min(A.KS),max(B.KS),min(B.KS) from
A inner join B on A.id=B.id
where A.id=1;

说明:
max(A.KS):A表KS最大值
min(A.KS):A表KS最小值
max(B.KS):B表KS最大值
min(B.KS):B表KS最小值
---
以上,希望对你有所帮助。

select case when t.a>t.b then t.a else t.b end as MAXKS,
case when t.c>t.d then t.d else t.c end as MINKS
from
(selsect max(A.KS) a,min(A.KS) b,max(B.KS) c,min(B.KS) d from
A inner join B on A.id=B.id
where A.id=1)t

借用了2楼老兄的代码,稍加改动。