需求如下:表A
---------------
jcode    CombId
000001     1
000031     1
000031     2通过select jcode from A where CombId=@CombId
可选出jcode
表B
--------------------------
jcode      RpID    Value
000001       1     300000
000031       2     500000
000001       3     100000
000031       4     200000
表C
-------------------------
jcode     RpID      date
000001     1        2008-3-1
000031     2        2008-3-1
000001     3        2008-3-2
000031     4        2008-3-2
现在要通过参数@CombId求出jcode在表B Value值的汇总,条件是RpID等于表C的对应jcode的date字段的最大时间我原来想用的语句是:
select sum(Value) from B where jcode in(select jcode from A where CombId=@CombId)
and RpID in(select RpID from C where jcode in(select jcode from A where CombId=@CombId))这样显然是不行的,后面的RpID就乱了,请高手的指教!!!

解决方案 »

  1.   

    select sum(value)
    from tb b inner join  
    (select *
    from tc c 
    where not exists(select 1 from tc where jcode = c.jcode and date > a.date)) c
    on b.jcode = c.jcode and b.rpid = c.rpid
    where exists (select 1 from ta where jcode = b.jcode and  CombId=@CombId )
      

  2.   

    -- Test Data: ta
    If object_id('ta') is not null 
        Drop table ta
    Go
    Create table ta(jcode varchar(6),CombId int)
    Go
    Insert into ta
    select '000001',1 union all
    select '000031',1 union all
    select '000031',2 
    Go
    -- Test Data: tB
    If object_id('tB') is not null 
        Drop table tB
    Go
    Create table tB(jcode varchar(6),RpID int,Value int)
    Go
    Insert into tB
    select '000001',1,300000 union all
    select '000031',2,500000 union all
    select '000001',3,100000 union all
    select '000031',4,200000 
    Go
    -- Test Data: tC
    If object_id('tC') is not null 
        Drop table tC
    Go
    Create table tC(jcode varchar(6),RpID int,date smalldatetime)
    Go
    Insert into tC
    select '000001',1,'2008-3-1' union all
    select '000031',2,'2008-3-1' union all
    select '000001',3,'2008-3-2' union all
    select '000031',4,'2008-3-2' 
    Go
    --Start
    select sum(value) 
    from tb b inner join  
    (select * 
    from tc c 
    where not exists(select 1 from tc where jcode = c.jcode and date > c.date)) c 
    on b.jcode = c.jcode and b.rpid = c.rpid 
    where exists (select 1 from ta where jcode = b.jcode and  CombId=1 )
    --Result:
    /*
    ----------- 
    300000(所影响的行数为 1 行)*/
    --End 
      

  3.   

    SELECT SUM(VALUE)
         FROM TB B 
         LEFT JOIN (SELECT T.JCODE,T.RPID FROM TC T 
                         WHERE NOT EXISTS(SELECT 1 FROM TC WHERE JCODE = T.JCODE AND DATE > A.DATE)) A 
                    ON B.JCODE = A.JCODE AND B.RPID = A.RPID 
    WHERE B.JCODE IN (SELECT JCODE FROM TA WHERE COMBID=@COMBID )