日期:2014-05-20  浏览次数:20621 次

一sql面试题

如图:表tab
现在需要写出:在termid为000001,000002,000003的记录中求BatchNo数值最大时各个termid对应的balanceNo的数值,即用sql描述:
000001 最大的BatchNo 12 此时对应的balanceNo数值是12
000002 最大的BatchNo 5 此时取得对应的balanceNo是190
000003 。。。。24 。。。。。..。。。。。。。。79


------解决方案--------------------

select termid,balanceNo from tab where termid in (select max(termid) from tab group by termid)
------解决方案--------------------
探讨
select termid,balanceNo from tab where termid in (select max(termid) from tab group by termid)

------解决方案--------------------
LS 貌似都没注意 他这张表是没有主键的。
楼主的方法 貌似是可以的。
为什么在sqlserver下运行不了,可以换种方法

select termid,balanceNo from tab where exists ( 
select * from (select termid,max(batchNo) as batchNo from tab where termid in('000001','000002','000003') group by termid
) a where a.termid=tab.termid and a.batchNo =tab.batchNo
)
------解决方案--------------------
select termid,batchNo,balanceNo 
from tab a,(select termid,max(batchNo) as batchNo from tab where termid in('000001','000002','000003') group by termid) b
where a.termid=b.termid and a.batchNo=b.batchNo
------解决方案--------------------
mysql测试没问题
select TermId,max(BatchNo),BalanceNo from term where TermId in (1,2,3) group by TermId
------解决方案--------------------
这个情况我在项目中遇到过

SQL code


Select Termid,BatchNo,BalanceNo from tab a  where BatchNo=(Select Max(BatchNo) from tab where Termid=a.Termid group by Termid)