从行之间共享的最后日期中选择所有值

时间:2020-05-28 17:12:45

标签: sql postgresql

我有一个Postgresql表,其中包含一段时间内国家/地区的计数。并非每个国家/地区都有每个日期的计数,有些国家/地区具有NULL值。我想获取每个国家/地区的计数,直到每个国家/地区拥有数据的日期为止,。

我做了一个DB Fiddle with example data

示例:

country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Germany 2020-05-27  12     3
Germany 2020-05-28  13     4
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
Italy   2020-05-27  22     7
Italy   2020-05-28  23     8
France  2020-05-25  30     9
France  2020-05-26  31     10
France  2020-05-27  NULL   11

我想找回以下信息:

country date        count  id
Germany 2020-05-25  10     1
Germany 2020-05-26  11     2
Italy   2020-05-25  20     5
Italy   2020-05-26  21     6
France  2020-05-25  30     9
France  2020-05-26  31     10

我已经搜索过,但是我对SQL比较陌生,而且似乎不知道要搜索哪些关键字。

1 个答案:

答案 0 :(得分:2)

您可以使用窗口函数来计算带有日期的行数,然后将其与国家/地区数量进行比较:

SELECT c.*
FROM (SELECT c.*, COUNT(count) over (partition by date) as num_countries_on_date
      FROM countries c
     ) c
WHERE num_countries_on_date = (SELECT  COUNT(DISTINCT c2.country) FROM countries c2);

Here是db <>小提琴。

如果您想为某个日期范围生成数据(这是相反的问题),则可以使用CROSS JOIN生成行,使用LEFT JOIN引入数据,然后COALESCE()NULL变成0

SELECT c.country, d.date, coalesce(co.count, 0) as count
FROM (SELECT DISTINCT country FROM countries) c CROSS JOIN
     generate_series('2020-05-26'::date, '2020-05-27'::date, interval '1 day') d(date) LEFT JOIN
     countries co
     ON co.country = c.country AND co.date = d.date;