日期(NCHAR)名称 号码1  号码2    序号  标记      日期(NCHAR)  名称    号码1    号码2      序号    标记 
  
20060101    #    A1      B1      2    M        
20060101    *    A1      B1      8    N      20060101      *      A1      B1        8      N 
20060101        A1      B1      7 20060104    #    A2      B2      9    P 
20060105    *    A2      B2      6    Q      20060105      *      A1      B1        6      Q 
20070101    #    A1      B1      4    K 
20070102        A2      B2      7    L 
20090102    *    A1      B1      0    L      20090102      *      A1      B1        0      L 
20090102    ¥    A1      B1    5    K      20090102      ¥      A1      B1        5      K 
20090105    *    C1    D1      1            20090105        *    C1      D1          1    G 要求:      当 左表中的 号码1+号码2相同,日期也相同时 ,输出序号大的那一行 
            当 左表中的 号码1+号码2相同,但日期不同时 ,输出日期大的那一行 
            当 左表中的 号码1+号码2+日期唯一时,也要该记录,不考虑序号 
            大前提:只选 名称为*或者¥的,名称为空的、#的不要 如右图的结果  
刚开始学SQL  碰到个难题 

解决方案 »

  1.   

    select * from tab a
    where 名称 in ('*','¥')
    and not exists (
      select 1 from tab
      where 名称 in ('*','¥')
      and 号码1=a.号码
      and 号码2=a.号码2
      and (日期>a.日期
      or 日期=a.日期
      and 序号>a.序号)
      )
      

  2.   


    declare @tb table (日期 nvarchar(10),号码1 nvarchar(10),号码2 nvarchar(10),序号 int,标记 nvarchar(5))
    insert into @tb select '20060101','A1','B1',2,'M'
          union all select '20060101','A1','B1',8,'N'
          union all select '20060104','A2','B2',9,'P'
          union all select '20060105','A2','B2',6,'Q'
    --select * from @tb a where 
    -- exists (select 1 from @tb where 号码1=a.号码1 and 号码2=a.号码2 )
    select * from 
    (select * from @tb a where not exists (select * from @tb where 号码1=a.号码1 and 号码2=a.号码2 and 日期>a.日期)) a 
    where not exists (select 1 from 
    (select * from @tb a where not exists (select * from @tb where 号码1=a.号码1 and 号码2=a.号码2 and 日期>a.日期))b where a.号码1=b.号码1 and b.序号>a.序号)  
    日期         号码1        号码2        序号          标记
    ---------- ---------- ---------- ----------- -----
    20060101   A1         B1         8           N
    20060105   A2         B2         6           Q(2 行受影响)