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

时间:2018-03-04 18:02:45

标签: sql excel postgresql

我可以在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。

1 个答案:

答案 0 :(得分: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