无意间翻到之间整理的一个讨论SQL语句的整理,觉得还是挺有意思的,发上来分享分享。SQL语句-期间变动表最近记录查询 
青岛哈哈猫 2008-02-15 07:53:25 回复 转载到 锁帖 修改 删除 
题目:  
   期间变动表table(产品编号,日期,数量),中记载着产品在不同时间的数量,现需查出针对每一种产品的最近时间的数量。此处,针对同一产品,在同一时间,只会出现一条记录。  
    
要求:用一条SQL语句来实现。      在以往的处理时,一般都是在存储过程里通过临时表做了中转,但是总觉得过于繁琐,而且在构建DW或者DS的时候,来源是存储过程还是有些修改不方便,或者会觉得大材小用了o(∩_∩)o…。  
    年前正好在群里请教了大家,现总结如下:  
1) ben:  
    在ben的讨论中,首先是提出了用Having。  
    select 产品编号,数量  
    from table a  
    having 日期 = (select max(日期) from table where 产品编号 = a.产品编号)       我们来看看having子句的介绍:  
    HAVING子句——指定组或聚合的搜索条件。HAVING通常与GROUP BY 子句一起使用。如果 不使用GROUP BY 子句,HAVING的行为与WHERE子句一样。      结合上面的介绍,我们知道:此处不易采用HAVING      接下来,ben提出的是:  
    select a.产品编号,a.数量  
    from table a  
    where a.日期 = (select max(日期) from table where 产品编号 = a.产品编号)  
2) 玉儿:  
    玉儿借用的是之前的一个语法:取班级的前三名。  
    select   产品,数量,日期   from   表   a   where    
   (select   COUNT(1)   FROM   表     
   where   产品=a.产品  and   日期>a.日期 )<=0     
3) 老奀:(老奀的名字很难打o(∩_∩)o…)  
   select * from table where convert(char(8),date,112)+pid in ( select max(convert(char(8),date,112)+pid from table group pid)   
      
   ***针对老奀的观点,ben做了一下优化,如下:  
   select a.proc_id, a.num  
   from (  
   select '2008-01-01' as dt, 'A' as proc_id, 100 as num from dual  
   union  
   select '2008-01-02' as dt, 'A' as proc_id, 200 as num from dual  
   union  
   select '2008-01-01' as dt, 'B' as proc_id, 150 as num from dual  
   union  
   select '2008-01-03' as dt, 'B' as proc_id, 100 as num from dual  
   ) a  
   where exists (select 1 from (  
   select '2008-01-01' as dt, 'A' as proc_id, 100 as num from dual  
   union  
   select '2008-01-02' as dt, 'A' as proc_id, 200 as num from dual  
   union  
   select '2008-01-01' as dt, 'B' as proc_id, 150 as num from dual  
   union  
   select '2008-01-03' as dt, 'B' as proc_id, 100 as num from dual  
   )   
   group by proc_id   
   having max(dt) = a.dt and a.proc_id = proc_id  
   )   4) 白貂:  
    select a.产品编号, b.日期, a.数量  
    from table a  
    (select 产品编号, max(日期) from table group by 产品编号) as b  
    where a.产品编号=b.产品编号 and  a.日期=b.日期       还有其他朋友的很多意见,就不一一列举了。非常感谢大家的支持,如果有写的不对的地方,还请轻点拍啊o(∩_∩)o…。