仅选择具有最近日期的项目

时间:2013-01-30 22:04:45

标签: date select plsql

我有下表:

create table weights (
   ident int references users,
   dateW date,
   weight float,
   primary key(ident,dateW)
);

我想仅选择具有最近日期的给定用户(身份)的权重。我有:

SELECT WEIGHT
FROM WEIGHTS
WHERE WEIGHTS.IDENT = 22 AND WEIGHTS.DATEW = (SELECT MAX(WEIGHTS.DATEW)
                                              FROM WEIGHTS);

但它没有做我想要的。建议?

3 个答案:

答案 0 :(得分:2)

您可以使用子查询:

SELECT w.WEIGHT
FROM WEIGHTS w
INNER JOIN
(
    SELECT MAX(DATEW) MaxDATEW
    FROM WEIGHTS 
) w1
    on w.DATEW= w1.MaxDATEW
WHERE w.IDENT = 22 

或者您可以申请row_number()

select *
from
(
    SELECT w.WEIGHT, row_number() over(order by w.DATEWdesc) rn
    FROM WEIGHTS w
    WHERE w.IDENT = 22 
) s
where rn = 1

答案 1 :(得分:1)

您的查询可能遇到的问题是,可能会从其他用户处获取最长日期,在这种情况下您将无法获得结果。子查询应该只获取同一用户的最大日期。

SELECT WEIGHT
FROM WEIGHTS
WHERE WEIGHTS.IDENT = 22 
AND WEIGHTS.DATEW = (
    SELECT MAX(WEIGHTS.DATEW)
    FROM WEIGHTS
    WHERE WEIGHTS.IDENT = 22
);

答案 2 :(得分:0)

SELECT 
  max(WEIGHT) keep (dense_rank first order by datew desc) as latest_weight
FROM WEIGHTS
WHERE WEIGHTS.IDENT = 22;