2014-09-30 26 views
0

我試圖創建一個查詢。我有兩個表Postgresql中如何做百分比

  • customercustomer_id
  • rentalrental_date(時間戳),customer_id
SELECT to_char(rental_date, 'Month') AS month, 
     (count(Distinct customer.customer_id)/ 
      (count (distinct rental.customer_id) * 100) 
     ) AS percentage 
FROM RENTAL,customer 
GROUP BY month; 

但結果卻是零。

回答

2

當一個操作涉及的所有「數字」都是整數時,結果也是一個整數。

試試這個方法:

SELECT 
    to_char(rental_date, 'Month') AS month, 

    (
    count(distinct customer.customer_id)::float/
    (count(distinct rental.customer_id)::float * 100::float) 
) 
    as percentage 

FROM 
    RENTAL,customer 
GROUP BY month;