-1

I have the table A

conipk    contittle concycle  ttlid

122786  108405  S13 107552    
122787  108405  S13 107552    
122788  108405  S13 107552    
122789  108405  S13 107552   

Table b

conipk    contype    concile   conamt
122786    LU     N         5.000
122786    LU         N         7.000
122787    LU     N         1.000
122788    LU     N         3.000
122788    LU         N         1.000
122789    LU     N         1.000

I want the 3 columns and the first record from table B.

The result desired is

conipk    contittle concycle  ttlid   contype concile conanmt

122786  108405    S13       107552    LU     N    5
122787  108405    S13       107552    LU     N    1
122788  108405    S13       107552    LU     N    3
122789  108405    S13       107552    LU     N    1

I did the query

SELECT      
   rc.contype, rc.concile, rc.conamtt, c.conipk, c.concycle, c.ttlid
FROM
   Contract c  
LEFT JOIN
   (SELECT TOP 1 
        r.conipk, r.contype, r.concile, r.conamt 
    FROM
        rules r 
    JOIN  
        contract c2 ON r.conipk = c2.conipk) AS rc ON rc.conipk = c.conipk 

But I just get the first record.

Thanks in advance

4

1 回答 1

0

问题是您只加入 B 的一条记录,而不是每个 key一条记录。

由于您没有说明您正在使用哪个服务器软件,因此很难得出明确的答案,但这将在 SQL Server 2005 及更高版本中起作用(前提是您提供了正确的顺序来确定“第一条”记录):

SELECT      
    rc.contype, 
    rc.concile,
    rc.conamtt,
    c.conipk,
    c.concycle,
    c.ttlid
FROM contract c  
LEFT JOIN  ( 
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY r.conipk ORDER BY ???) RowNUm,
        r.conipk,
        r.contype,
        r.concile,
        r.conamt 
        from rules r 
        join contract c2 on r.conipk = c2.conipk ) AS rc  
    on  c.conipk = rc.conipk
        AND rc.RowNum = 1
于 2013-08-08T20:55:45.340 回答