2016-12-19 53 views
0

我正在構建將幾個表連接在一起的報表。一切都完美地減去了一個方面。我需要cost2字段才能顯示最高的成本。基本上,一件物品通過生產經歷了幾次成本變化,最終成本是最高的。我需要查詢最終成本。我知道它是一個簡單的解決方案,但我掙扎得比我應該做得更多。SQL Server - 按最高值過濾

下面是我的查詢的簡化示例:
MAX函數無法按照我的預期工作。

SELECT DISTINCT table1.item_no, 
       table2.quantity, 
       table2.date, 
       table3.cost1, 
       MAX(table4.cost2) 
FROM table1 
    INNER JOIN table2 ON table2.item_no = table1.item_no 
    INNER JOIN table3 ON table3.item_no = table1.item_no 
    INNER JOIN table4 ON table4.item_no = table1.item_no 
WHERE table3.cost1 <> 0 
GROUP BY table1.item_no, 
     table2.quantity, 
     table2.date, 
     table3.cost1 
+1

如何確定最終成本? –

+0

是最後一個INNER上的拼寫錯誤而不是句號嗎? 'table1,item_no'應該是'table1.item_no' – xQbert

+0

你可以定義「不按我的意圖嗎?」?如果我打算根據模糊的描述爲您的查詢定義一些僞代碼,它看起來就像您發佈的內容。幫助我們瞭解問題,並幫助您找到解決方案。這裏是一個開始的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

1
SELECT table1.item_no, 
     table2.quantity, 
     table2.date, 
     table3.cost1, 
     table4.cost2 
FROM table1 
    INNER JOIN table2 ON table2.item_no = table1.item_no 
    INNER JOIN table3 ON table3.item_no = table1.item_no 
    INNER JOIN table4 ON table4.item_no = table1,item_no 
WHERE table3.cost1 <> 0 
AND table4.cost4 = (SELECT MAX(a.cost4) 
        FROM table4 a 
        WHERE 
         table4.item_no=a.item_no 
         GROUP BY a.item_no 
        ) 
1

我想你想要row_number()

SELECT t.* 
FROM (SELECT t1.item_no, t2.quantity, t2.date, t3.cost1, t4.cost2, 
      row_number() over (partition by t1.item_no order by t4.cost2 desc) as seqnum 
     FROM table1 t1 INNER JOIN 
      table2 t2 
      ON t2.item_no = t1.item_no INNER JOIN 
      table3 t3 
      ON t3.item_no = t1.item_no INNER JOIN 
      table4 t4 
      ON t4.item_no = t1.item_no 
     WHERE t3.cost1 <> 0 
    ) t 
WHERE seqnum = 1; 

因爲你似乎想每個項目的一個排,partition by只包含的項目數。你會得到所有其他列成本最高的行。