select * from fty_sjgz t where ny in('2009-07','2009-08','2009-09')
and  not exists 
(select 1 from fty_sjgz where gz > t.gz and mem_id = t.mem_id and ny in('2009-07','2009-08','2009-09'))
order by mem_idselect mem_id,max(gz) as gz from fty_sjgz where ny in('2009-07','2009-08','2009-09')
group by mem_id两种写法出来的行数不同,为什么?

解决方案 »

  1.   

    前面的写法可以得到fty_sjgz表所有的字段的值
    后面的写法只能得到mem_id,和最大的gz
      

  2.   

    --try
    select * from (
    select * from fty_sjgz t where ny in('2009-07','2009-08','2009-09'))a
    where  not exists 
    (select 1 from (
    select * from fty_sjgz t where ny in('2009-07','2009-08','2009-09'))b where b.gz > a.gz and b.mem_id = a.mem_id )
    order by mem_id
      

  3.   


    ---类似的,好像一样的if object_id('tb') is not null drop table tb
    go 
    create table tb(id int,name varchar(10))
    insert tb select
    1,'A' UNION ALL SELECT
    2,'A' UNION ALL SELECT
    3,'B' UNION ALL SELECT
    4,'B' UNION ALL SELECT
    5,'B' UNION ALL SELECT
    6,'C' UNION ALL SELECT
    7,'C'  select * from tb t where name in('A','B')
    and  not exists 
    (select 1 from TB where ID > t.ID and NAME = t.NAME and name in('A','B'))
    order by NAMEselect max(ID)as ID , NAME  from TB where name in('A','B')
    group by NAME
    id          name       
    ----------- ---------- 
    2           A
    5           B(所影响的行数为 2 行)ID          NAME       
    ----------- ---------- 
    2           A
    5           B(所影响的行数为 2 行)
      

  4.   

    select mem_id,max(gz) as gz from fty_sjgz where ny in('2009-07','2009-08','2009-09')
    group by mem_id第二条写法是:
    1,先找出ny等于那三个月的记录;
    2,然后在才在上面找到的记录里进行查询,
    3,所以第二条查询并非从整个表里查询.第一条写法是:从整个表里查询
      

  5.   

    gz 列有 null 值吗?