在PostgreSQL中,如果我有这样的记录:
|------------------|---------------------|------------------|
| corona_country | corona_patient | corona_suspected |
|------------------|---------------------|------------------|
| Mexico | Teddy | 2020-03-01 |
|------------------|---------------------|------------------|
| Indonesia | Andy | 2020-03-01 |
|------------------|---------------------|------------------|
| Indonesia | Andy | 2020-03-05 |
|------------------|---------------------|------------------|
| China | Sarah | 2020-03-04 |
|------------------|---------------------|------------------|
| UK | Michael | 2020-03-05 |
|------------------|---------------------|------------------|
| Italy | Michael | 2020-03-15 |
|------------------|---------------------|------------------|
| Italy | Michael | 2020-03-15 |
|------------------|---------------------|------------------|我想添加额外的列(通过选择查询)来标识corona_country和corona_patient的组合是否在自己的记录中有最新的日期( corona_suspected列)。看起来是这样的:
|------------------|---------------------|------------------|-----------|
| corona_country | corona_patient | corona_suspected | LATEST? |
|------------------|---------------------|------------------|-----------|
| Mexico | Teddy | 2020-03-01 | Y |
|------------------|---------------------|------------------|-----------|
| Indonesia | Andy | 2020-03-01 | N |
|------------------|---------------------|------------------|-----------|
| Indonesia | Andy | 2020-03-05 | Y |
|------------------|---------------------|------------------|-----------|
| China | Sarah | 2020-03-04 | Y |
|------------------|---------------------|------------------|-----------|
| UK | Michael | 2020-03-05 | Y |
|------------------|---------------------|------------------|-----------|
| Italy | Michael | 2020-03-13 | N |
|------------------|---------------------|------------------|-----------|
| Italy | Michael | 2020-03-15 | Y |
|------------------|---------------------|------------------|-----------|
| Italy | Michael | 2020-03-15 | Y |
|------------------|---------------------|------------------|-----------|如何通过sql查询实现这一点?是否有任何方法连接另一个表,该表记录corona_country和corona_patient的每个组合的最新日期?
发布于 2020-03-16 16:13:24
使用窗口函数:
select t.*,
(rank() over (partition by corona_country, corona_patient order by corono_suspected desc) = 1
) as is_latest
from t;请注意,这将创建一个布尔值。如果您想要字符串,请使用case
select t.*,
(case when rank() over (partition by corona_country, corona_patient order by corono_suspected desc) = 1
then 'Y' else 'N'
end) as is_latest
from t;https://stackoverflow.com/questions/60709444
复制相似问题