每行返回同一行中第1列和第2列设置的范围内的元素数

问题描述 投票:0回答:1

我可以在excel中轻松完成这项工作(参见图片了解所需结果)。

enter image description here

下面是一些示例代码和使用SUM()的失败尝试。

使用低值和高值作为范围,对于每一行计算行KeyNms在该范围内的KeyNums列中出现的次数。

请注意,CASE1确实返回正确的计数,但它使用的是硬编码值。

我正在寻找一种动态的方法。 CASE2为每一行返回TRUE,因此是所有行的计数。

我想我可能需要一个函数或某种类型的数组?

我有什么想法可以做到这一点?

SELECT low, high, "KeyNms",
        sum(case when "KeyNms" between 35  and 57   then 1 end) over(partition by "KeyNms" between 35  and 57) as "Case1",
        sum(case when "KeyNms" between low and high then 1 end) over(partition by "KeyNms" between low and high) as "Case2"
FROM
    (SELECT l-11 as low, l+11 as high, l as "KeyNms"
        FROM generate_series(1,100,5) as l(n)
        group by l.n
     ) as t
group by "KeyNms", low, high
order by "KeyNms"

使用PostgreSQL 9.6。

sql excel postgresql
1个回答
1
投票
create table range (low int, hight int);
create table keys (keynum int);
insert into range values (3,12),(6,9),(24,40);
insert into keys values (1),(4),(7),(10),(13),(16),(19),(22),(25),(28),(31),(34),(37),(40),(43);

您可以使用标量子查询:

select low, hight, (select count(*) 
                    from   keys
                    where  keynum between low and hight) count 
from   range;
low | hight | count
--: | ----: | ----:
  3 |    12 |     3
  6 |     9 |     1
 24 |    40 |     6

或者在低和高之间的keynum上使用JOIN:

select low, hight, count(keys.*)
from   keys
join   range
on     keynum between low and hight
group by low, hight;
low | hight | count
--: | ----: | ----:
  3 |    12 |     3
  6 |     9 |     1
 24 |    40 |     6

dbfiddle here

© www.soinside.com 2019 - 2024. All rights reserved.