sql 取最大与最小值语句
if object_id('tb') is not null drop table tb;
go
create table tb(
col1 int,
col2 int,
fcount int)
insert into tb
select 11,20,1 union all
select 11,22,1 union all
select 11,23,2 union all
select 11,24,5 union all
select 12,39,1 union all
select 12,40,3 union all
select 12,38,4
go
--查询
--1
select * from tb t where fcount=(select max(fcount)from tb where col1=t.col1)
--2
select * from tb t where not exists(select 1 from tb where col1=t.col1 and fcount>t.fcount)
--结果
/*
col1 col2 fcount
----------- ----------- -----------
12 38 4
11 24 5
*/
实例二
商品进货报价表中保存有n种商品,每种商品分别对应m个供货商的报价,我想得到这样一个结果:从一个表中一眼能看出每种商品对应的最低商家报价和最高商家报价,怎么做呢?
1)新建一个数据库教程 test.mdb
2)导入info.mdb 和 info1.mdb 的数据表,分别为 info 和 info1,表的数据如下:
info
————–
商品名称
1234
2345
info1
—————————
商品名称 厂商 价格
1234 厂商1 10
1234 厂商2 20
1234 厂商3 30
2345 厂商1 40
2345 厂商2 50
2345 厂商3 60
3456 厂商1 70
3456 厂商2 80
3456 厂商3 90
3)新建一个查询,打开 sql视图 (视图->sql视图)
4)粘贴如下内容并运行
select info1.名称, max(info1.价格) as 价格之最大值, min(info1.价格) as 价格之最小值
from info1
group by info1.名称
having info1.名称 in ( select info.名称 from info);
5)运行结果如下:
查询1:选择查询
———————————–
商品名称 价格之最大值 价格之最小值
1234 30 10
2345 60 40