我想解决以下问题:
为每种运动类型指定区域10中事件的百分比与该运动类型的事件总数。
我有两张桌子:
活动:列出所有体育赛事。 “sport_type”列定义了事件的体育类型;它有一个点几何。
区域:列出名称为ex的所有区域。 '地区10'。它们有一个多边形几何。
列出我所拥有的每种运动类型的赛事数量:
select e.sport_type as Sport_Type, count(e.sport_type) as Number_of_Events
from events e
group by e.sport_type
要列出区域10中每种运动类型的事件数量,我有:
select e.sport_type as Sport_Type, count(e.sport_type) as Number_of_Events
from events e
inner join zones z
on st_contains(z.geom, e.geom)
where z.name = 'region 10'
group by e.sport_type
要解决这个问题,我尝试了类似的东西,但它不起作用:
select e1.sport_type as Sport_Type, (x.Numev / count(e1.sport_type)) as Number_of_Events
from events e1, (select e2.sport_type as evtype, count(e2.sport_type) as Numev
from programs e2
inner join zones z
on st_contains(z.geom, e2.geom)
where z.name = 'region 10'
group by e2.sport_type) x
group by e1.sport_type, x.Numev
答案 0 :(得分:1)
使用两个子选择会创建一个非常不言自明的查询:
SELECT sport_type, 100. * r10.total / sports.total AS r10_percent
FROM (
SELECT sport_type, count(sport_type) AS total
FROM events
GROUP BY sport_type) sports
JOIN (
SELECT sport_type, count(sport_type) AS total
FROM events
JOIN zones ON ST_Contains(zones.geom, events.geom)
WHERE zones.name = 'region 10'
GROUP BY events.sport_type) r10 USING (sport_type);
答案 1 :(得分:0)
尚未测试,只是尝试,因为您有多少事件,您可以轻松计算百分比(例如:在外面选择1个以上)
select
e.sport_type as Sport_Type,
count(*) as totalEvents,
sum(CASE
WHEN z.name = 'region 10' THEN 1
ELSE 0
END
) as totalEventsInRegion10
from events e
left join zones z on st_contains(z.geom, e.geom)
group by e.sport_type