2013-01-06 42 views
2

我一直在努力使用SQL Server查詢一段時間,並意識到我必須從知道SQL Server(很多)的人那裏得到更多幫助。從SQL Server中獲取最大值加入

環境:SQL Server 2008中

SELECT  
    t1.SUPPL_ORDERNO, 
    t2.OUR_ORDER, 
    t3.CUST_INVOICE 
FROM t1 

    LEFT OUTER JOIN t2 
     ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 

    LEFT OUTER JOIN t3 
     ON t2.ORDER_REM5 = t3.INV_REM5 

GROUP BY t1.SUPPL_ORDERNO, t2.OUR_ORDER, t3.CUST_INVOICE 
ORDER BY t1.SUPPL_ORDERNO,t3.CUST_INVOICE 

這是結果我用上面的查詢得到:

SUPPL_ORDERNO     OUR_ORDER CUST_INVOICE 
------------------------------ --------- ------------ 
143914       64228  179890 
143914       64228  179935 
143914       64228  179995 
143914       64228  179999 
143914       64228  180067 
143914       64228  180148 
326042         
326052       64549  180219 
326086       64633 

我得到每個SUPPL_ORDERNOOUR_ORDER組合的多個CUST_INVOICE但我只想要回最新的CUST_INVOICE(=最大的發票號碼)。

這是我想要返回的結果:

SUPPL_ORDERNO     OUR_ORDER CUST_INVOICE 
------------------------------ --------- ------------ 
143914       64228  180148 
326042         
326052       64549  180219 
326086       64633 

摘要:

  1. 如果有超過一(1)CUST_INVOICE因爲我只想展現SUPPL_ORDERNOOUR_ORDER組合CUST_INVOICE與最大數
  2. 如果沒有OUR_ORDER和否CUST_INVOICE我希望它顯示爲空
  3. ,如果有一個OUR_ORDER沒有CUST_INVOICE我想它顯示爲空

任何幫助,將不勝感激!

回答

1

解決此問題的最佳方法是使用row_number()。這通過發票號增加了序列號的事情,在這種情況下,每個訂單中:

select suppl_orderno, our_order, cust_invoice 
from (SELECT t1.SUPPL_ORDERNO, t2.OUR_ORDER, t3.CUST_INVOICE, 
      row_number() over (partition by t1.SUPPL_ORDERNO, t2.OUR_ORDER order by t3.cust_invoice desc) as seqnum 
     FROM t1 LEFT OUTER JOIN 
      t2 
      ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 LEFT OUTER JOIN 
      t3 
      ON t2.ORDER_REM5 = t3.INV_REM5 
    ) t 
where seqnum - 1 
ORDER BY SUPPL_ORDERNO,CUST_INVOICE 

通過以降序排序發票,最近獲得的「1」的值,它用於過濾。

2

從GROUP BY刪除t3.CUST_INVOICE並使用MAX(t3.CUST_INVOICE)函數爲SELECT語句

SELECT t1.SUPPL_ORDERNO, t2.OUR_ORDER, MAX(t3.CUST_INVOICE) AS CUST_INVOICE 
FROM t1 LEFT JOIN t2 ON t1.SUPPL_ORDERNO = t2.ORDER_REM5 
     LEFT JOIN t3 ON t2.ORDER_REM5 = t3.INV_REM5 
GROUP BY t1.SUPPL_ORDERNO, t2.OUR_ORDER 
ORDER BY t1.SUPPL_ORDERNO, t3.CUST_INVOICE 

簡單的例子在SQLFiddle