数据库是SQLSERVER的。表名:收发记录,有记录样式如下:
ID   名称   数量   售价  日期
120   A      10     2    2008-04-30  //需要的第一条
12   B       9     2.8    2008-04-12
22   A       16     2    2008-04-10 //需要的第二条 
11   C       10     2.1   2008-04-11
6    A       16     1.8    2008-03-30
2    A       16     2    2008-03-10 //本条售价虽然相同他的日期最一个售价为1.8元的不同售价之前所以不要它。要求找到名称为A的售价相同的记录,且日期为最后面及最近的记录的数量和、最小的日期
及售价.即要求取出“需要的第一条和需要的第二条”两条记录的数量和、取出最小日期“2008-04-10” 取出售价 2请问这样的SQL语句如何写???

解决方案 »

  1.   


    select a.*
      from (select 名称, 售价
              from mytable
             GROUP BY 名称, 售价
            HAVING count(1) >= 2) b,
           mytable a
     where a. 名称 = b. 名称
       and a. 售价 = b. 售价
       and 日期 >= '2008-4-1'
       and 日期 <= '2008-4-30'
       and a. 名称 = 'a'
     ORDER BY a. 日期----结果
    /*
    22 A 16 2.000 2008-04-10 00:00:00.000
    120 A 10 2.000 2008-04-30 00:00:00.000
    */
      

  2.   


    --注意表名,我用的表名是mytableselect * from mytable where [id] in(
    select min(id) mytable from (select  a.* from( 
    select [名称],[售价]  from mytable GROUP BY [名称],[售价] 
    HAVING count(1)>=2) b,mytable a 
    where a.[名称]=b.[名称] 
    and a.[售价]=b.[售价] 
    and [日期]>='2008-4-1' 
    and [日期]<='2008-4-30' 
    and a.[名称]='a'
    )l
    UNION all 
    select max(id) mytable from (select  a.* from( 
    select [名称],[售价]  from mytable GROUP BY [名称],[售价] 
    HAVING count(1)>=2) b,mytable a 
    where a.[名称]=b.[名称] 
    and a.[售价]=b.[售价] 
    and [日期]>='2008-4-1' 
    and [日期]<='2008-4-30' 
    and a.[名称]='a'
    )v)----结果
    /*
    22    A    16    2.000    2008-04-10 00:00:00.000
    120    A    10    2.000    2008-04-30 00:00:00.000
    */