是否可以将此外部应用转换为左连接?

时间:2015-07-10 01:50:50

标签: sql-server sql-server-2000 apply outer-join

SELECT
    hb.custnum,hb.custname as Cname,dv.custname as [CustName],'0' + hb.cellnum as cellnum,dv.ccelnumber,
    UPPER(hb.subd) as subd,UPPER(dv.BilStAdd) as BilStAdd,hb.entity,dv.BilCtAdd
FROM [cust] as dv
OUTER APPLY (
    SELECT TOP 1 * FROM ##custnumtbl WHERE ##custnumtbl.CustNum = dv.custnum ORDER BY totaldue DESC
) hb
Where 
    '0' + hb.cellnum <> dv.ccelnumber    
    or RTRIM(LTRIM(hb.custname)) <> RTRIM(LTRIM(dv.CustName)) 
    or UPPER(hb.subd) <> RTRIM(LTRIM(UPPER(dv.BilStAdd)))
    or UPPER(hb.entity) <> RTRIM(LTRIM(UPPER(dv.BilCtAdd)))

2 个答案:

答案 0 :(得分:1)

(注意:在写完这个答案后,OP识别出数据库。它不适用于SQL Server 2000.)

是的,如果你愿意的话。最简单的方法是使用窗口函数,例如row_number()

SELECT hb.custnum,hb.custname as Cname, dv.custname as [CustName],
       '0' + hb.cellnum as cellnum, dv.ccelnumber,
       UPPER(hb.subd) as subd,UPPER(dv.BilStAdd) as BilStAdd,hb.entity,dv.BilCtAdd
FROM [cust] dv LEFT JOIN
     (SELECT c.*,
             ROW_NUMBER() OVER (PARTITION BY c.CustNum ORDER BY totaldue DESC) as seqnum
      FROM ##custnumtbl c
     )  hb
     ON hb.CustNum = dv.custnum AND seqnum = 1
WHERE '0' + hb.cellnum <> dv.ccelnumber  or
      RTRIM(LTRIM(hb.custname)) <> RTRIM(LTRIM(dv.CustName)) or
      UPPER(hb.subd) <> RTRIM(LTRIM(UPPER(dv.BilStAdd))) or
      UPPER(hb.entity) <> RTRIM(LTRIM(UPPER(dv.BilCtAdd)));

我认为outer apply可能会有更好的表现。

答案 1 :(得分:0)

对于SQL Server 2000:

SELECT
    hb.custnum,hb.custname as Cname,dv.custname as [CustName],'0' + hb.cellnum as cellnum,dv.ccelnumber,
    UPPER(hb.subd) as subd,UPPER(dv.BilStAdd) as BilStAdd,hb.entity,dv.BilCtAdd
FROM [cust] as dv
LEFT JOIN(  
    SELECT b.*
    FROM (
        SELECT CustNum, totaldue = MAX(totaldue)
        FROM ##custnumtbl
        GROUP BY CustNum
    )a
    INNER JOIN ##custnumtbl b
        ON b.CustNum = a.CustNum
        AND b.totaldue = a.totaldue
)hb
    ON hb.CustNUm = dv.custnum
Where 
    '0' + hb.cellnum <> dv.ccelnumber    
    or RTRIM(LTRIM(hb.custname)) <> RTRIM(LTRIM(dv.CustName)) 
    or UPPER(hb.subd) <> RTRIM(LTRIM(UPPER(dv.BilStAdd)))
    or UPPER(hb.entity) <> RTRIM(LTRIM(UPPER(dv.BilCtAdd)))

正如M.Ali所指出的,如果你没有使用区分大小写的排序规则,你可能想要摆脱UPPER