2015-07-10 61 views
1
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))) 
+1

如果您沒有使用'UPPER()'函數進行'CASE敏感整理'對查詢返回的結果沒有任何影響,但可能會影響查詢性能。 –

回答

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的。

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很可能有更好的表現。

+0

打敗我吧。我打算使用'ROW_NUMBER'發佈答案。 +1 –

+0

它適用於SQL 2008,但當我試圖在SQL 2000上運行它時,會發生此錯誤:'ROW_NUMBER'不是一個可識別的函數名稱。 ,這也是我試圖將我的應用查詢轉換爲左連接的原因 –

+0

這是因爲ROW_NUMBER不是SQL Sever 2000上的有效語法。 –