有一个产品表品名  规格 价格 公司ID 日期
 A     1    1     1    200-6-10-9
 A     1    1     1    200-6-10-10
 A     1    2     1    200-6-10-12
 B     2    1     2    200-6-10-12
 A     2    1     2    200-6-10-12
 A     2    1     2    200-6-10-13
 A     1    1     2    200-6-10-15现在需要统计 : 品名 规格都相同的同一公司的产品只要最新加入的,也就是选出下面的记录品名  规格 价格 公司ID 日期
 A     1    2     1    200-6-10-12
 B     2    1     2    200-6-10-12
 A     2    1     2    200-6-10-13
 A     1    1     2    200-6-10-15该如何写这个SQL语句啊?

解决方案 »

  1.   

    楼主的结果是不是有点问题啊~~~create table test(品名 nvarchar(2),规格 int,价格 int,公司ID int,日期 datetime)
    insert test
    select 'A',1,1,1,'2006-10-9' union all
    select 'A',1,1,1,'2006-10-10' union all
    select 'A',1,2,1,'2006-10-12' union all
    select 'B',2,1,2,'2006-10-12' union all
    select 'A',2,1,2,'2006-10-12' union all
    select 'A',2,1,2,'2006-10-13' union all
    select 'A',1,1,2,'2006-10-15'
    --select * from testselect * from test i where not exists 
    (
    select 1 from test where 品名=i.品名 and 规格=i.规格 and 日期>i.日期
    )drop table test
      

  2.   

    select a.* from producttb a,(select 品名, 价格,公司ID,convert(varchar(10),max(convert(datetime,日期),120) 日期 group by 品名, 价格,公司ID) b where a.品名=b.品名 and a.规格=b.规格 and a.日期>b.日期 and a.公司ID=b.公司ID
      

  3.   

    select * from 表名
    where (品名,规格,公司ID,日期) in (select 品名,规格,公司ID,max(日期) as 日期 from 
    表名 group by 品名,规格,公司ID)
      

  4.   

    select * from tab a , (select 品名,规格,公司ID,max(日期) from tab group by 品名,规格,公司ID) b
    where a.品名=b.品名,a.规格=b.规格,a.公司ID=b.公司ID
      

  5.   


    select * from A.* from 产品表
    innerjoin 
    (
    select 品名,规格,min(日期) 日期 
    from 产品表
    group by 品名,规格
    )B
    on A.品名=B.品名 
    and A.规格=B.规格
    and A.日期=B.日期
      

  6.   

    create table test(品名 nvarchar(10),规格 int,价格 int,公司ID int,日期 datetime)
    insert test
    select 'A',1,1,1,'2006-10-9' union all
    select 'A',1,1,1,'2006-10-10' union all
    select 'A',1,2,1,'2006-10-12' union all
    select 'B',2,1,2,'2006-10-12' union all
    select 'A',2,1,2,'2006-10-12' union all
    select 'A',2,1,2,'2006-10-13' union all
    select 'A',1,1,2,'2006-10-15'-----------------------
    select * from test a
    where not exists ( select * from test 
                        where a.品名=品名
                                   and a.规格=规格 
                                       and a.公司ID=公司ID
                                         and 日期>a.日期)drop table test---------------------------------
    a 1 2 1 2006-10-12 00:00:00.000
    b 2 1 2 2006-10-12 00:00:00.000
    a 2 1 2 2006-10-13 00:00:00.000
    a 1 1 2 2006-10-15 00:00:00.000
      

  7.   

    select 品名,规格,价格,公司ID,(select max(日期) from tablename group by 品名,规格) as 日期 group by 品名,规格 order by 日期