2017-02-13 116 views
2

我有這個sql語法,這很好。它顯示了用於獲取我們的源的數量。我希望數字以百分比顯示(100%以外),而不是數字顯示。我如何得到我的陳述以百分比顯示計數,請提供幫助Databasers。顯示周和年份的百分比

聲明:

select coalesce(t2.Source, 'Total') as "Source", 
     coalesce(count(case when Week = date_trunc('week', now())::date - 1 
           then t1."Source" end),0) "This Week", 
     coalesce(count(t1.Source),0) "YTD" 
from infosys t2 
    left join infocentertracker t1 
       ON t1.Source = t2.Source 
       and Week >= DATE '01/01/2017' 
       and Week < DATE '01/01/2018' 
       and Project_ID = 'PCR' 
group by rollup(t2.Source) 

結果:

Source   This Week YTD      This Week  YTD 
Billboard   0   0       0%   0% 
Builder   2   8       20%   12% 
Community Website 0   2       0%   3% 
Drive-by   6   35      60%   52% 
Non-Disclosed  0   1  Requested -->  0%   2% 
Other Website  0   4       0%   6% 
Radio    0   0       0%   0% 
Realtor   1   13      10%   19% 
Resident Referral 1   3       10%   4% 
Return Visitor  0   0       0%   0% 
RPG Website  0   0       0%   0% 
Social Media  0   2       0%   3% 
Total    10   68      100%  100% 
+0

你爲什麼使用'by rollup'? – McNets

+0

在查詢底部顯示總數。 –

+0

也許這裏需要一個窗口函數:http://stackoverflow.com/a/6207658/3430807 – Andreas

回答

2

我不知道這是否是最好的方式,但你可以使用現有的查詢作爲子查詢來獲取所需的結果以百分比表示使用MAX窗口函數。

SELECT Source, 
ROUND(100.0*"This Week"/ MAX(CASE WHEN Source='Total' THEN "This Week" END) OVER(),0)||'%' AS "This Week", 
ROUND(100.0*YTD/ MAX(CASE WHEN Source='Total' THEN YTD END) OVER(),0)||'%' AS YTD 
FROM 
(SELECT COALESCE(T2.Source, 'Total') AS "Source", 
      COALESCE(COUNT(CASE 
          WHEN WEEK = DATE_TRUNC('week', NOW())::date - 1 THEN T1."Source" 
         END),0) "This Week", 
      COALESCE(COUNT(T1.Source),0) "YTD" 
    FROM INFOSYS T2 
    LEFT JOIN INFOCENTERTRACKER T1 ON T1.Source = T2.Source 
    AND WEEK >= DATE '01/01/2017' 
    AND WEEK < DATE '01/01/2018' 
    AND PROJECT_ID = 'PCR' 
    GROUP BY ROLLUP(T2.Source) 
) X 
+0

感謝vkp,第一個選擇我試過't1.Source',它拋出了一個錯誤,'錯誤:缺少FROM-clause表「t1」的條目。任何想法如何我可以解決這個問題。 –

+0

@Pythoner ..你可以試試編輯過的版本嗎? –

+0

我再次編輯它..我假設'源'是區分大小寫的。請在內部查詢中相應地對其進行相應修改,並使用任一表中該列的確切大小寫。我用'Source' .. –