SQL Server - 按最高值过滤

时间:2016-12-19 15:53:47

标签: sql sql-server filter max

我正在构建一个将几张桌子连接在一起的报告。一切都完美地减去了一个方面。我需要cost2字段才能显示最高的成本。基本上,一个项目通过生产经历了几次成本变化,最终成本最高。我需要查询最终费用。我知道这是一个简单的解决方案,但是我的努力比我应该做的更多。

以下是我的查询的简化示例:
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  

2 个答案:

答案 0 :(得分: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仅包含项目编号。您将获得最高成本行的所有其他列。

答案 1 :(得分: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
                    )