2017-03-09 83 views
0

在我們的查詢工具(使用ODBC)4.1 我想獲得最大inv_shipment_date和相應的inv_billed_weight,product_ID和division_CD。 我有4個表格,我必須從(1必須用於加入其他)獲取數據。 我無法編寫SQL將結果下載到顯示最大出貨日期的一行。SQL Max函數檢索一個記錄與其他表中的相關字段

表和所需的字段:

FOS: Package_key Inv_Shipment_Date Inv_Billed_Weight Division_Key

FIF: Package_key Product_key

PD: Product_key PRODUCT_ID

DD: Division_Key Division_CD

最終結果,我在一個表 MAX(inv_shipment_date) Inv_Billed_Weight PRODUCT_ID Division_CD

我寫的是導致空白數據(我知道通過尋找希望在數據中最大出貨日期實際上是20170112,計費重量是20,部門是DOL,產品ID是03-01984-001)

我在做什麼錯?謝謝你的幫助smile.gif

SELECT 
max(fos.inv_shipment_date_key), 
dd.division_cd, 
pd.product_id, 
max(fos.inv_billed_weight) 


FROM DCDM.FREIGHT_OUT_SUMMARY fos, 
    (select max(inv_shipment_date_key) as Maxinvdate, inv_billed_weight 
    from dcdm.freight_out_summary 
    group by inv_billed_weight) maxdate, 
dcdm.division_dim dd, 
dcdm.product_dim pd, 
dcdm.freight_invoice_fact fif 

where fos.inv_billed_weight = maxdate.inv_billed_weight 
and fos.inv_shipment_date_key = maxdate.maxinvdate 
and fos.package_key = fif.package_key 
and fif.product_key = pd.product_key 
and fos.division_key = dd.division_key 
and pd.product_id = '03-01984-001' 

group by 
fos.inv_shipment_date_key, 
dd.division_cd, 
pd.product_id, 
fos.inv_billed_weight 
+0

您可以共享表的創建腳本以及一些示例數據的插入語句嗎? –

+0

最大inv_shipment_date_key在整個表中,或對於一組特定的Division_Key?提供一些示例數據和預期輸出 – Utsav

回答

0

如果我正確理解你的問題,你需要這樣的人。如果在最後一行刪除AND條件,則會得到所有product id的結果。我建議你刪除最後的AND條件,然後運行它,看看你是否得到期望的結果。但沒有樣本數據,這真的很難猜測。

SELECT * 
FROM 
    (SELECT Package_key, 
      Inv_Billed_Weight, 
      Division_Key, 
      row_Number() over (partition BY Division_Key 
          ORDER BY Inv_Shipment_Date DESC) AS rn 
    FROM DCDM.FREIGHT_OUT_SUMMARY) fos 
INNER JOIN dcdm.division_dim dd 
    ON fos.division_key = dd.division_key 
INNER JOIN dcdm.freight_invoice_fact fif 
    ON fos.package_key = fif.package_key 
INNER JOIN dcdm.product_dim pd 
    ON fif.product_key = pd.product_key 
WHERE fos.rn=1 
    AND pd.product_id = '03-01984-001' 
0

我假設你想要產品的MAX出貨日期,是否正確?如果是這樣,我建議最初在這裏使用子查詢,然後加入其他表(或者你可以先加入,但似乎沒有必要)。當然,這取決於你使用的標識符 - 如果你有一個「貨運ID」,這將是理想的。 例如:

select 
Max(table1.Inv_shipment_date) over (partition by table2.product_ID) as max_shipment_date, 
table1.SHIPMENT_ID, 
table2.product_Id, 
table3.division_Cd, 
table4.inv_billed_weight 

from 
(select 
SHIPMENT_ID, 
inv_shipment_date 

from table 1) as table1 

left join 
(select 
SHIPMENT_ID, 
product_ID 

from table 2) as table2 
on table 1.SHIPMENT_ID = table2.SHIPMENT_ID 

left join 
(select 
SHIPMENT_ID, 
division_Cd 

from table 3) as table3 
on table 1.SHIPMENT_ID = table3.SHIPMENT_ID 

left join 
(select 
SHIPMENT_ID, 
inv_billed_weight 

from table 4) as table4 
on table 1.SHIPMENT_ID = table4.SHIPMENT_ID 
相關問題