网络编程
位置:首页>> 网络编程>> 数据库>> 相同记录行如何取最大值

相同记录行如何取最大值

作者:德仔 来源:德仔Blog 发布时间:2008-07-26 12:32:00 

标签:记录,sql,数据,最大值

相同记录行如何取最大值

我想这个东西在作一些相关采购系统或成本报价系统应该很有用的吧

取当前的最有效的价格.记录下来

与大家分享!

--测试数据   
  create   table   #表A   (fid   int,fprice   dec(5,2),fsuid   int,fdate   datetime)   
  insert   #表A   select   1,           2.1,             2,               '2005-09-09'   
  insert   #表A   select   1,           2.2,             2,               '2005-10-10'   
  insert   #表A   select   1,           3.3,             2,               '2006-01-01'   
  insert   #表A   select   2,           3.3,             1,               '2003-09-09'   
  insert   #表A   select   2,           5.5,             1,               '2005-09-09'   
  insert   #表A   select   2,           3.2,             2,               '2005-09-09'   
  insert   #表A   select   2,           5.5,             2,               '2005-09-15'   
    
  --查询   
  select   distinct   a.*   from   #表A   a,(select   fid,fsuid,max(fdate)   as   'fdate'   from   #表A   group   by   fid,fsuid)   b   
  where   a.fid=b.fid   and   a.fsuid=b.fsuid   and   a.fdate=b.fdate   order   by   a.fid   
  /*结果   
  fid                   fprice     fsuid               fdate                                                                                                       
  -----------   -------   -----------   ------------------------------------------------------     
  1                       3.30         2                       2006-01-01   00:00:00.000   
  2                       5.50         1                       2005-09-09   00:00:00.000   
  2                       5.50         2                       2005-09-15   00:00:00.000   
    
  (所影响的行数为   3   行)
  
  
  求是最大日期对应的价格
  
  --Try   
    
  --测试数据   
  create   table   #A   (fid   int,fprice   dec(5,2),fsuid   int,fdate   datetime)   
  insert   #A   select   1,           2.1,             2,               '2005-09-09'   
  insert   #A   select   1,           2.2,             2,               '2005-10-10'   
  insert   #A   select   1,           3.3,             2,               '2006-01-01'   
  insert   #A   select   2,           3.3,             1,               '2003-09-09'   
  insert   #A   select   2,           5.5,             1,               '2005-09-09'   
  insert   #A   select   2,           3.2,             2,               '2005-09-09'   
  insert   #A   select   2,           5.5,             2,               '2005-09-15'   
    
  select   *   from   #A   a     
  where   not   exists   
  (select   1   from   #A   where   fid=a.fid   and   fsuid=a.fsuid   and   fdate>a.fdate)


3.取单条价格最大记录

 select   price,materialcode   from   UBS_CAS_PriceForm   a     
  where  materialcode='1140099' and  not   exists   
  (select   1   from   UBS_CAS_PriceForm   where   materialcode=a.materialcode  and     pubdate>a.pubdate)

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com