设为首页 加入收藏

TOP

sql 取最大与最小值语句
2011-06-12 21:38:10 来源: 作者: 【 】 浏览:315次 评论:0

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   

 

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇SQL UNION 和 UNION ALL语法与实例 下一篇mysql导出数据库几种方法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位