表结构如下:
品种  数量  销售日期     销售人
ad     1     2010-01-02   admin
ex     2     2010-02-02   admin
ad     3     2010-01-30   admin
ce     1     2010-03-03   admin
......
要求是取出各品种最后销售日期为最后(最大)的那条记录?求SQL查询语句?

解决方案 »

  1.   

    select * from 表 group by 品种 having max(销售日期) 不知道格式对不,仅提供思路,
    1 你肯定要通过GROUP BY 来分组
    2 用HAVING来取日期最大值
      

  2.   

    select 品种, max(日期) from table1 group by 品种
      

  3.   

    DECLARE @T TABLE (品种 VARCHAR(12), 数量 int, 日期 datetime, 销售人 varchar(12))
    INSERT INTO @T
    select 'ad', 1, '2010-01-02', 'admin' union all
    select 'ex', 2, '2010-02-02', 'admin' union all
    select 'ad', 3, '2010-01-30', 'admin' union all
    select 'ce', 1, '2010-03-03', 'admin' union all
    select 'ad', 1, '2010-03-02', 'admin' union all
    select 'ex', 2, '2010-02-16', 'admin' union all
    select 'ad', 3, '2010-02-12', 'admin' union all
    select 'ce', 1, '2010-02-13', 'admin' select * from @T where 品种+cast(日期 as varchar) in
    (select 品种+cast(max(日期) as varchar) from @T group by 品种)/* RESUTL
    ce 1 2010-03-03 00:00:00.000 admin
    ad 1 2010-03-02 00:00:00.000 admin
    ex 2 2010-02-16 00:00:00.000 admin
    */
      

  4.   

    GROUP BY 来分组,然后按排序来取值。
      

  5.   

    select * from  table1 where 日期 = (select  max(日期) from table1) group by 品种
      

  6.   

    定义存储过程调用,或者将这些语句连在一起看作一条sql语句直接运行应该就可以了
      

  7.   

    如果是取其中的 日期,品种,这两个字段,
    没什么好说的, 楼上的几种方法都行,
    但要字段全部显示出来,需要内查询 或用临时表select 品种, max(日期)AS Date INTO #temp1 from table1 group by 品种select * from table1 A
    INNER JOIN temp1  B ON A.品种= B.品种 and A.日期=B.Date 
      

  8.   

    表明假设为table,个字段为type、qty、date、usr
    SQL语言为:
    select t1.*
    from table as t1 left outer join table as t2 on t1.type = t2.type
    and t1.date < t2.date
    group by t1.type, t1.qty, t1.date, t1.usr
    having sum(case when t2.type is null then 0 else 1 end) < 1但这种方法的缺陷是:如果有几笔资料都是最后一天的,则都会查出来。
    如果只希望出一笔资料,可将table存入一个临时表中,并增加一个identity字段,左连接条件中增加对这个字段的比较条件应该就可以了。注:以上方法应该只适用于SQL Server
      

  9.   

    2楼的正解,将分组查出的结果集作为B表,再与原表A进行关联即可
    select a.* from 原表 a,
    (select 品种, max(销售日期) maxdate from 原表 group by 品种) b 
    where a.品种=b.品种 and a.销售日期=b.maxdate;