2016-08-26 53 views
1

我有四個這樣的列。當另一列在oracle中具有不同的值時,如何使用MAX(列)選擇行?

Material Description Quantity   Date 
    a   133  200  26-09-2016 12:33 
    a   133  400  27-09-2016 10:33 

我需要從該材料的數量,當最大(日期);

我試過這個,但是如果數量是不同的顯示兩行。

Select material , description , quantity , max(date) 
FROM materials 
group by material, description , quantity 
+0

在你的where子句中使用max date .. – XING

+0

什麼版本的Oracle? (總是聲明,如果你不知道,通過運行'select * from v $ version'找到。)在Oracle 12中,你可以使用'fetch first | last'並避免子查詢。 – mathguy

回答

2

使用在WHERE子句條件像

Select material , description , quantity 
FROM materials 
WHERE "Date" = (select max("Date") from materials) 
0

可以使用row_number()這樣的(我'加入材料B,如果你需要找到在組中的所有材料量「a」和「 b「):

WITH a(Material, Description , Quantity , sDate) AS 
    (SELECT 'b', 133, 1200 , to_date('26-09-2016 12:33','dd-mm-yyyy hh24:mi') FROM dual UNION ALL 
    SELECT 'b', 133, 2200 , to_date('29-09-2016 12:33','dd-mm-yyyy hh24:mi') FROM dual UNION ALL 
    SELECT 'a', 133, 200 , to_date('26-09-2016 12:33','dd-mm-yyyy hh24:mi') FROM dual UNION ALL 
    SELECT 'a', 133, 400 , to_date('27-09-2016 10:33','dd-mm-yyyy hh24:mi') FROM dual ) 
SELECT * 
    FROM (SELECT a.*, 
       row_number() over(partition BY material order by sdate DESC) rn 
      FROM a) 
WHERE rn = 1 


MATERIAL DESCRIPTION QUANTITY SDATE    RN 
-------- ----------- ---------- --------- ---------- 
a    133  400 27-SEP-16   1 
b    133  2200 29-SEP-16   1 
1

使用RANK() analytic function

SELECT * 
FROM (
    SELECT materials, 
     description, 
     quantity, 
     date, 
     RANK() OVER (PARTITION BY materials ORDER BY date DESC) AS rnk 
    FROM materials 
) 
WHERE rnk = 1; 

如果存在具有相同materials和最大date值的行,則這將獲得多行 - 如果您只需要一行,則使用ROW_NUMBER()而不是RANK()

0
SELECT * 
FROM (
    SELECT materials, 
     description, 
     quantity, 
     date, 
     RANK() OVER (PARTITION BY materials ORDER BY date DESC) AS rnk 
    FROM materials 
) 
WHERE rnk = 1; 
相關問題