2017-10-22 80 views
0

我有一個查詢,可以獲得一個城市的投訴數量。從蟒蛇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)/(從數據SELECT COUNT(*))'我想。 –

回答

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

我明白這一點。你碰巧知道爲什麼我會得到一個錯誤:沒有這樣的列:city_name? – GenXeral

+0

nvm。我將cc部分更改爲cc.city_name – GenXeral

+0

代碼中沒有錯誤,但由於某些原因,我的所有比率均爲0。 – GenXeral