sql - 判断表中的条目是否在增加

标签 sql postgresql

我有一个临时表(人员文本、年份整数、计数整数)。它存储

person, year, count
("a",2009,1),
("a",2010,2), 
("a",2011,3), 
("a",2012,4),
("b",2010,1),
("b",2011,2),
("b",2012,3), 
("c",2011,1),
("d",2009,4),
("d",2010,4), 
("d",2011,4), 
("d",2012,4),
("e",2009,1),
("e",2010,2),
("e",2012,4)

我应该告诉您,从 2009 年到 2012 年,哪些人的计数严格增加,计数始终为正整数。对于给定的表,输出将是“a”和“b”。请注意,“b”也严格增加,因为它在 2009 年的计数为 0(我知道上面写的计数必须为正有点奇怪,现在我说它在 2009 年为 0,但它只是给出就像问题中那样)。

预期输出:- 在给定的表格中,a 从 2009 年到 2012 年严格增加。这很酷。对于 b,它缺少 2009,但我们将其视为零(准确地说,names 是作者的姓名,count 是他们发表的论文数量 - 我们必须找到那些在 2010 年发表论文的作者比 2009 年发表的论文多, 2011 年比 2010 年和 2012 年比 2011 年,所以 count=0 确实有意义)。所以对于 b,2009 年是 0。因此,序列是 0、2、3、4 - 严格递增。不应打印 c,因为 2009 和 10 中的计数均为零。类似地,d 不应打印,因为它的计数是常量。不应该打印 e,因为取 0 后,它的序列变成 1, 2, 0, 4。所以,a 和 b 应该是唯一的输出。

我的尝试:- 我尝试使用滞后函数,但存在问题,因为它无法区分 2009 年是否存在。我也可以在其中使用计数,但那样我将无法区分哪个不存在。什么是最佳解决方案?谢谢!

最佳答案

使用 generate_series() 与表左连接获取具有完整counts 的数据:

select year, person, coalesce(count, 0) as count
from generate_series(2009, 2012) as year
cross join (
    select distinct person
    from temp
    ) p
left join temp using(year, person)
order by 2, 1

 year | person | count 
------+--------+-------
 2009 | a      |     1
 2010 | a      |     2
 2011 | a      |     3
 2012 | a      |     4
 2009 | b      |     0
 2010 | b      |     1
 2011 | b      |     2
 2012 | b      |     3
 2009 | c      |     0
 2010 | c      |     0
 2011 | c      |     1
 2012 | c      |     0
 2009 | d      |     4
 2010 | d      |     4
 2011 | d      |     4
 2012 | d      |     4
 2009 | e      |     1
 2010 | e      |     2
 2011 | e      |     0
 2012 | e      |     4
(20 rows)

对结果使用array_agg() 来找到满足条件的:

select person, array_agg(count order by year) as counts
from (
    select person, year, coalesce(count, 0) as count
    from generate_series(2009, 2012) as year
    cross join (
        select distinct person
        from temp
        ) p
    left join temp using(year, person)
    ) s
group by person
having  array_agg(distinct count order by count) = array_agg(count order by year)

 person |  counts 
--------+-----------
 a      | {1,2,3,4}
 b      | {0,1,2,3}
(2 rows)    

关于sql - 判断表中的条目是否在增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279192/

相关文章:

sql - 在 MySQL 中获取死锁

mysql - 基于 SQL Server 的有限时间段内的小组系列

PostgreSQL 基于多个条件更新列

java - 使用 Java 将图像上传到 PostgreSQL

postgresql - Pgcrypto 命令产生非标准输出

Sqlite 获取最大 ID 不起作用(?)

mysql - 计算每小时的元素数量,然后求结果的平均值

sql - "CONTAINS"是否有任何 MySQL 聚合函数?

postgresql - 外键的大小(以字节为单位)?

python - Psycopg2 字符串格式,带有用于创建类型的变量名