我有一个查询可以获取某个城市的投诉数量。
query = '''
select ComplaintType as complaint_type, City as city_name,
count(ComplaintType) complaint_count
from data
where city in ({})
group by city_name, complaint_type
order by city_name
'''.format(strs_to_args(TOP_CITIES))
ComplaintType City_name。投诉_
现在,我想创建一个列来计算城市中发生的类型t的投诉。它会像count(ComplaintType)/ sum(城市中的count(ComplaintType))
实现此目的的最佳语法是什么?
query = '''
select ComplaintType as complaint_type, City as city_name,
count(ComplaintType)/sum(count(ComplaintType) as complaint_freq
答案 0 :(得分:1)
好吧,一种方法是在子查询中进行汇总并将结果加入:
query = '''
select d.ComplaintType as complaint_type, d.City as city_name,
count(*) as complaint_count,
count(*) * 1.0 / max(cc.cnt) as ratio
from data d cross join
(select d.city, count(*) as cnt
from data d
group by d.city
) cc
on d.city = cc.city
where d.city in ({})
group by d.city, d.complaint_type
order by d.city
'''.format(strs_to_args(TOP_CITIES))