使用group_id与整个表执行每列的代码块

时间:2018-03-05 01:57:23

标签: sql postgresql

由于McNets的一点帮助,我有这个完美的代码块,直到我添加一个组列。
我一直在尝试使用窗口子句和子查询的多种方法,但还没有找到可行的解决方案。

我一直在研究这个问题几个小时 - 在这一点上,我想我可能太接近代码看不到光...... 我哪里错了?

我已经包含了好的和坏的结果的图片。每个组应具有相同的值。 使用PostgreSQL 9.6

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);

没有grp列的代码:

select low, hight, count(k.*)
from   keys k
join   range r
on     keynum between low and hight
group by low, hight 

添加grp列时失败的代码:

select grp, low, hight, count(*) over(partition by grp)
from   keys k
join   range r
on     keynum between low and hight
group by grp, low, hight
order by grp, low, hight

子查询也失败了:

select * from (
    select grp, low, hight, count(*)
    from   keys k
    join   range r
    on     keynum between low and hight
--where grp = 2
group by grp, low, hight
order by grp, low, hight) t

results without grp column

results with grp column

results using subquery

1 个答案:

答案 0 :(得分:0)

你有group by,你不需要窗口功能。这是你想要的吗?

select grp, low, hight, count(*)
from keys k join
     range r
    on keynum between low and hight
group by grp, low, hight
order by grp, low, hight;

窗口函数count(*) over (partition by grp)计算每个grp值的聚合之后的行数。有三排。这就是“3”的来源。