2017-10-22 12 views
0

都市の苦情の件数を取得するクエリがあります。今python sqlクエリの合計からのパーセンテージ/パーセンテージの計算

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 .Complain_

、私は街で発生した型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

'数(ComplaintType)/'私は思います。 –

答えて

1

、1つの方法は、サブクエリでまとめるとで結果を参加することである:(データからSELECT COUNT(*))

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)) 
+0

私はこれを理解しています。なぜ私はエラーが発生するのか知っていますか?そのような列はありません:city_name? – GenXeral

+0

nvm。 ccの部分をcc.city_nameに変更しました – GenXeral

+0

コードにエラーはありませんが、何らかの理由ですべての比率が0になっています。 – GenXeral