用于计数子部分的窗口查询

时间:2014-05-09 17:25:25

标签: sql postgresql count

我正在尝试计算一个区域内的工作数量并计算该区域中每种工作类型的数量。

我认为解决方案是一个窗口查询,我已经阅读了大量的窗口查询问题,我仍然无法弄明白。我不明白我应该如何撰写查询。

我用于计算某个区域中作业数量的运行查询是:

SELECT region.id, count(*) as total_jobs
FROM region_center INNER JOIN region 
ON ST_DWithin(region_center.geom, region.geom, 2640)
GROUP BY region.id;

我认为,这个想法是进行查询,然后从该查询中选择:

WITH T1 AS (
SELECT region.id, region.job
FROM region_center INNER JOIN region 
ON ST_DWithin(region_center.geom, region.geom, 2640)
)
 SELECT
  (SELECT id FROM T1 GROUP BY id),
  (SELECT count(*) FROM T1 GROUP BY id) as Total,
  (SELECT count(*) from T1 where job = 'Janitor' GROUP BY id) as Janitor
  (SELECT count(*) from T1 where job = 'Repair' GROUP BY id) as Repair
;

但这显然不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

select
    region.id,
    count(*) as total_jobs,
    count(job = 'Janitor' or null) as "Janitor"
    count(job = 'Repair' or null) as "Repair"
from
    region_center
    inner join
    region on st_dwithin(region_center.geom, region.geom, 2640)
group by region.id;