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
销量
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查询语句,求每个分组中的最大值实例
- sql查询语句,求每个分组中的最大值实例
- sql查询语句,求每个分组中的最大值实例
- SQL语句查询每个分组的前N条记录的实现方法
- 使用SQL语句查询每个分组的前N条记录
- SQL查询得到(按编号分组的日期最大的记录)
- [VB.NET]用SQL查询得到(按编号分组的日期最大的记录)
- yii 使用原生sql 查询 以某一字段分组 每个字段取出最新的一条数据
- 数据库排名sql,group by 分组查询按照时间最大值
- SQL查询每个分组的前N条记录
- Sql 查询每个年级中,年龄最大的两个学生信息。。。
- sql分组查询每组的最大值
- [MS SQL]SQL语句查询每个分组的前N条记录的实现方法
- SQL语句查询每个分组的前N条记录的实现方法
- 分组查询最大/最小值sql
- SQL查询每个分组的前N条记录
- sql 分组后查询最大所有列信息
- 数据库排名sql,group by 分组查询按照时间最大值
- [MS SQL]SQL语句查询每个分组的前N条记录的实现方法
- SQL语句:查询出每个分组的前若干条记录