您的位置:首页 > 数据库

sql 查询每个分组最大的值

2012-03-09 15:37 288 查看
年           产品      
销量  

  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql join 百度 产品 c