0

我有下表:

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

我只想从最近日期的给定用户(ident)中选择重量。我有:

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

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

4

3 回答 3

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
于 2013-01-30T22:09:02.260 回答
1

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

SELECT WEIGHT
FROM WEIGHTS
WHERE WEIGHTS.IDENT = 22 
AND WEIGHTS.DATEW = (
    SELECT MAX(WEIGHTS.DATEW)
    FROM WEIGHTS
    WHERE WEIGHTS.IDENT = 22
);
于 2013-01-30T22:12:22.367 回答
0
SELECT 
  max(WEIGHT) keep (dense_rank first order by datew desc) as latest_weight
FROM WEIGHTS
WHERE WEIGHTS.IDENT = 22;
于 2013-01-30T22:28:55.803 回答