sql 查询每个分组最大的值

来源:互联网 发布:科比与乔丹数据对比 编辑:程序博客网 时间:2024/05/21 22:43

年           产品      
销量  
  2005       a             700  
  2005       b             550  
  2005       c             600  
  2006       a             340  
  2006       b             500  
  2007       a             220  
  2007       b             350  
   
  我要得到  
  2005       a           700  
  2006       b           500  
  2007       b           350  
  怎么做?  

select   *   from   tb   a   where   not   exists(select   *   from   tb   where   年=a.年   and   销量>a.销量)    
   
  --or:  
  select   *   from   tb   a   inner   join   (select   年,max(销量)   as   销量   from   tb   group   by   年)b  
  on   a.年=b.年   and   a.销量=b.销量  



表结构:
id carId dateChange
1 001 2007-5-1
2 001 2007-5-2
3 002 2007-9-1
4 002 2007-9-9
需要得到每种carId中,dateChange最大的那条记录,对于现在这几条记录来说,就是要得到第2条和第四条。
谢谢!!!


select
t.*
from
表 t
where
not exists(select 1 from 表 where carId=t.carId and dateChange>t.dateChange)

三 自链接查询

以前只是听说过 表查询的自连接,一直没有用过
今天突然看百度知道上一个网友在问一个查询问题
 
表名:车过站表(passStation)
字段 车次 顺次 站点
        110    1     上海
        110    2     南京
         112   1     北京
         110    3    浙江
         110    4    江苏
。。。。。。。。。。。。。
假如要查询经过南京和江苏的车次
可以通过自连接来解决
 
select r1.checi from test r1,test r2
where r1.checi=r2.checi and(
r1.chezhan='江苏' and r2.chezhan='南京')  

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1694571