子查询帮助 Postgres

Subquery help Postgres

我的架构中有 2 个 table:

1 - covid_data(相关列:国家、年份、周、案例)。数据示例:

+-------+------+-----+-------+
|country| year | week| cases |
+-------+------+-----+-------+
|USA    | 2022 |  1  | 58488 |
|USA    | 2022 |  2  | 65154 |
|USA    | 2022 |  3  | 74154 |
|USA    | 2022 |  4  | 84158 |
|USA    | 2022 |  5  | 96997 |
+-------+------+-----+-------+

countries_of_the_world(相关栏目:国家)

+-------+
|country|
+--------
|USA    | 
|France | 
|Brazil | 
|Germany| 
|China  | 
+-------+

我需要检索 countries_of_the_world 中每个国家/地区的最新记录。 “最近记录”的规则由 的较高值和 的较高值决定。例如,现在是 2022 年第 6 周。

我做了以下代码:

SELECT country, max(year), max(week) 
FROM covid_data
WHERE week in (
    SELECT MAX(week)
    FROM covid_data
    WHERE year in (
        SELECT MAX(year)
        FROM covid_data
        GROUP BY year) 
    GROUP BY week)
GROUP BY country;

但正在检索分开的信息。例如,第 53 周 表示 2022 年,因为本周在过去一年中“可用”:

+--------------------+
|country| year | week|
+--------------------+
|USA    | 2022 | 53  |
+--------------------+

如何执行此查询,包括将每个国家/地区与其他国家/地区联合起来table?

未经测试,但以下内容是否符合您的要求?

with c as (
  select country, cases, 
    Row_Number() over(partition by country order by year desc, week desc) rn
  from covid_data
)
select country, cases
from c
where rn = 1;