我有四个这样的列。
Material Description Quantity Date
a 133 200 26-09-2016 12:33
a 133 400 27-09-2016 10:33
我需要在Max(Date);
时从该材料中获取数量我试过这个但是如果数量不同则显示两行。
Select material , description , quantity , max(date)
FROM materials
group by material, description , quantity
答案 0 :(得分:2)
在WHERE
子句中使用该条件,如
Select material , description , quantity
FROM materials
WHERE "Date" = (select max("Date") from materials)
答案 1 :(得分:1)
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()
答案 2 :(得分:0)
你可以像这样使用row_number()(如果你需要找到组中所有材料的数量" 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
答案 3 :(得分:0)
SELECT *
FROM (
SELECT materials,
description,
quantity,
date,
RANK() OVER ( PARTITION BY materials ORDER BY date DESC ) AS rnk
FROM materials
)
WHERE rnk = 1;