首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql 查询某字段最大值对应的另一个字段的值解决方案

2012-03-22 
sql 查询某字段最大值对应的另一个字段的值表:afinteridfitemidfprice1a12b23c24a35b4...finterid 字段没

sql 查询某字段最大值对应的另一个字段的值
表:a

finterid fitemid fprice
  1 a 1
  2 b 2
  3 c 2
  4 a 3
  5 b 4
  .
  .
  .

finterid 字段没有重复的值

我自己写的语句使这样的:
select fitemid, max(FInterid),fprice from a group by Fitemid,fprice order by a.fitemid
因为我把fprice也group by 了,所以得出的结果的话,例如这个表,fitemid有有行值,
fprice不group by 的话,又语法错误~其他的聚合函数也没一个适用的,怎么办呢

[解决办法]

SQL code
select *  from a twhere not exists(select 1 from a where t.fitemid=fitemid and t.FInterid<FInterid)
[解决办法]
假如有最大值的记录是多笔怎么办哪?

实际上你需要在得出最大值的结果集上再链接查询出对应的记录。

#1楼 的结果就符合你的要求。
但是还是会存在对应最大值的记录有多笔的问题
[解决办法]
SQL code
select a.* from 表a  a inner join (select  max(FInterid) as maxf from 表a group by fitemid) b on a.finterid=b.maxf
[解决办法]
如果你要取的是finterid的最大值,那么直接这样就一了
SQL code
select a.* from 表a  a inner join (select  max(FInterid) as maxf from 表a) b on a.finterid=b.maxf 

热点排行