create table tb(单据号 int, 进价 int, 货物编码 int)
insert into tb
select 1, 6, 10 union all
select 2, 10, 11 union all
select 3, 10, 12 union all
select 4, 10, 10 union all
select 5, 2, 11
select * from tb a where not exists (select 1 from tb where 货物编码=a.货物编码 and 单据号>a.单据号)
order by 货物编码/*
单据号 进价 货物编码
------------------------
4 10 10
5 2 11
3 10 12
*/
drop table tb
insert into tb
select 1, 6, 10 union all
select 2, 10, 11 union all
select 3, 10, 12 union all
select 4, 10, 10 union all
select 5, 2, 11
select * from tb a where not exists (select 1 from tb where 货物编码=a.货物编码 and 单据号>a.单据号)
order by 货物编码/*
单据号 进价 货物编码
------------------------
4 10 10
5 2 11
3 10 12
*/
drop table tb
解决方案 »
- select @@version
- 同一个服务器上两个数据库之间做数据转移 求语句
- 如何将int[][]数组存入数据库中?
- sql server 2008 正在挂起更改
- 如何用SQL成批更新数据表内容?
- 请分析下面的SQL语句where部份怎样写
- 如何随机抽取数据
- SQL server 数据更新问题
- 有什么好办法加密sql server的表的字段名吗?
- 使用image类型数据时总是出错,特向高手请教!
- 查询需要单位范围约束(界面TreeView选定范围),但单位范围可能是一个集合,存储过程不好传集合,怎么实现单位约束?高手请进!!!谢谢!
- [100 分求高手帮忙] 树节点复制问题,数据库该如何写 ?
insert into tb
select 1, 6, 10 union all
select 2, 10, 11 union all
select 3, 10, 12 union all
select 4, 10, 10 union all
select 5, 2, 11 --一、按货物编码分组取进价最大的值所在行的数据。
--方法1:
select a.* from tb a where 进价 = (select max(进价) from tb where 货物编码 = a.货物编码) order by a.货物编码
--方法2:
select a.* from tb a where not exists(select 1 from tb where 货物编码 = a.货物编码 and 进价 > a.进价)
--方法3:
select a.* from tb a,(select 货物编码,max(进价) 进价 from tb group by 货物编码) b where a.货物编码 = b.货物编码 and a.进价 = b.进价 order by a.货物编码
--方法4:
select a.* from tb a inner join (select 货物编码 , max(进价) 进价 from tb group by 货物编码) b on a.货物编码 = b.货物编码 and a.进价 = b.进价 order by a.货物编码
--方法5
select a.* from tb a where 1 > (select count(*) from tb where 货物编码 = a.货物编码 and 进价 > a.进价 ) order by a.货物编码drop table tb/*
单据号 进价 货物编码
----------- ----------- -----------
4 10 10
2 10 11
3 10 12(所影响的行数为 3 行)
*/
再描述清楚点:表的主键是单据号+编码,是一个进货表,想通过一个SQL语句找出所有货物最近一次进货的进价。