【问题标题】:Expand resultset across array values跨数组值扩展结果集
【发布时间】:2019-04-16 09:38:09
【问题描述】:

我正在运行一些报告查询,我想将每条记录的结果扩展为一组特定的 4 周。

这是当前查询:

select
  job_id,
  week,
  count(*),
  sum(count(*)) over (partition by job_id)
from candidates
group by job_id, week

当前结果

 job_id | week | count | sum 
--------+------+-------+------
   3258 |    1 |    21 |  23 
   3258 |    2 |     2 |  23 
   3259 |    1 |     1 |   4 
   3259 |    4 |     1 |   4 

但理想情况下,我想在 4 周的特定范围内进行扩展:

期望的结果

 job_id | week | count | sum 
--------+------+-------+-----
   3258 |    1 |    21 |  23 
   3258 |    2 |     2 |  23 
   3258 |    3 |     0 |  23 # added row with 0 count
   3258 |    4 |     0 |  23 # added row with 0 count
   3259 |    1 |     1 |   4 
   3259 |    2 |     0 |   4 # added row with 0 count
   3259 |    3 |     0 |   4 # added row with 0 count
   3259 |    4 |     1 |   4 

使用 LEFT JOIN 不会返回所需的结果,如您在此 SQL fiddle 中看到的那样

架构 (PostgreSQL v9.6)

CREATE TABLE candidates(
   job_id integer,
   week integer,
   count1 integer,
   sum1 integer
);

INSERT INTO candidates(job_id, week, count1, sum1) VALUES (3984, 1, 13, 26);
INSERT INTO candidates(job_id, week, count1, sum1) VALUES (3984, 2, 13, 26);

INSERT INTO candidates(job_id, week, count1, sum1) VALUES (3985, 1, 42, 46);
INSERT INTO candidates(job_id, week, count1, sum1) VALUES (3985, 4, 3, 46);

查询 #1

select
  c.job_id,
  weeks.week_nr as week,
  c.count1,
  c.sum1
from generate_series(1,4) as weeks(week_nr)
left join candidates c on c.week = weeks.week_nr 
order by c.job_id, week;
| job_id | week | count | sum |
| ------ | ---- | ----- | --- |
| 3984   | 1    | 1     | 2   |
| 3984   | 2    | 1     | 2   |
| 3985   | 1    | 1     | 2   |
| 3985   | 4    | 1     | 2   |
| null   | 3    | null  | null|

【问题讨论】:

  • 在 SQLfiddle 中,您使用 generate_series() 并获得预期结果。
  • 使用 Join 而不是 left join 那么你会得到没有空值。

标签: postgresql join group-by


【解决方案1】:

在 postgresql 中,我们可以获取使用的范围值 generate_series()(或)where 条件

 select job_id,week,count(*),sum(count(*)) over (partition by job_id)
 from generate_series(1,4) as weeks(week_nr)
 left join candidates c on c.week = weeks.week_nr 
 group by job_id, week order by job_id,week;

                       (or)

 select job_id,week,count(*),sum(count(*)) over (partition by job_id)
 from candidates where week>=1 and week<=4
 group by job_id, week;

【讨论】:

  • 遗憾的是,这不会产生预期的结果。查看更新的说明。
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2016-06-02
  • 2013-06-11
相关资源
最近更新 更多