一张表(t_value)中有如下字段:
id  主键,每条记录的id
Fid  外键, 另一张表的主键
theMinValue   该条记录取值区间的最小值
theMaxValue 该条记录取值区间的最大值然后我插入如下数据:
insert into t_value values(1, 10, 1000, 2000);
insert into t_value values(2, 10, 2000, 3000);
insert into t_value values(3, 10, 3000, 4000);
insert into t_value values(4, 10, 4000, 5000);
insert into t_value values(5, 10, 5000, null); //特殊说明,如果theMaxValue字段值为null,则代表无穷大
insert into t_value values(7, 20, 1000, 2000);
insert into t_value values(8, 20, 2000, 3000);
insert into t_value values(9, 20, 3000, 4000);
insert into t_value values(10, 20, 4000, 5000);
insert into t_value values(11, 20, 5000, null); //特殊说明,如果theMaxValue字段值为null,则代表无穷大可以看出一个Fid可以关联多个记录,现在我要查出已Fid分组,并取出分组中theMaxValue值最大的记录,即我要得到的结果是就是上面两条特殊说明的记录。我写的查询语句是这样的:select id, Fid, theMinValue, theMaxValue from t_value 
inner join(select Fid as maxValueFid, (case when theMaxValue is null then null else max(theMaxValue) end) as maxValue from t_value )
on Fid = maxValueFid and theMaxValue = maxValue但是查询的结果为空,请问我写的查询语句哪里错了?另外,有没有更好的查询方式呢?

解决方案 »

  1.   

    额。。我知道查询结果为空的原因了,null不能使用=来判断。。应该这样写:
    select id, Fid, theMinValue, theMaxValue from t_value 
    inner join(select Fid as maxValueFid, (case when theMaxValue is null then null else max(theMaxValue) end) as maxValue from t_value )
    on Fid = maxValueFid and (theMaxValue = maxValue or theMaxValue is null)这样就能查出想要的结果。但是有没有更好的查询方式呢?有idea的求不吝赐教!
      

  2.   

    参考下贴中的多种方法http://blog.csdn.net/acmain_chm/article/details/4126306
    [征集]分组取最大N条记录方法征集,及散分....