2012-09-10 57 views
1

我有sql table,裏面有2列用戶標識和產品,用戶標識是唯一的,產品有3個值[0,1,-1] -1代表沒有產品購買,1代表產品目前使用 ,而0表示產品已被使用。查找產品對客戶總數的百分比

我想要的是表中所有用戶的百分比查詢
產品使用率(%):?
目前正在使用的產品(%):?
產品未售出(%):?

任何建議或幫助,將不勝感激 感謝

enter image description here
我至今嘗試過?

Select count(userId) * 100/(select count(products) Where products = 1) AS perc 
from product group by userid 
+3

這是相當簡單 - 你嘗試過什麼到目前爲止,並沒有你會得到什麼錯誤? –

+0

我試着寫一些像選擇計數(userId)* 100 /(選擇計數(產品)其中產品= 1)作爲從產品組按用戶ID perc,但它不起作用 –

+0

「不工作」不是一個足夠的錯誤描述。請更精確。 –

回答

4

試試這個:

SELECT SUM(CASE WHEN products = 1 THEN 1 ELSE 0 END) * 100 /
Count(DISTINCT Products.UserID) AS 'Currently used products%', 
SUM(CASE WHEN products = 0 THEN 1 ELSE 0 END) * 100 /
Count(DISTINCT Products.UserID) As 'Used products%', 
SUM(CASE WHEN products = -1 THEN 1 ELSE 0 END) * 100 /
Count(DISTINCT Products.UserID) AS 'Not sold products%' 
FROM Products 
+2

'DISCOUNT'?我不認爲這是存在的。 –

+2

再也不會在會議中使用SO了:) :)謝謝:) –

+0

SUM(產品)也會總結-1值 –

0
SELECT products, 
(convert(numeric(5,2),count(products))/(SELECT convert(numeric(5,2),count(products)) FROM product)) * 100 
AS "Percentage" 
FROM product GROUP BY products 
+0

爲什麼要轉換爲'numeric(5,2)'? – Kash

1
SELECT SUM(CASE WHEN Products = 1 THEN 1 ELSE 0 END) * 100 
    /COUNT(DISTINCT UserID) AS product_currently_in_use_pct 
    , SUM(CASE WHEN Products = 0 THEN 1 ELSE 0 END) * 100 
     /COUNT(DISTINCT UserID) AS product_used_pct 
    , SUM(CASE WHEN Products = -1 THEN 1 ELSE 0 END) * 100 
    /COUNT(DISTINCT UserID) AS product_not_sold_pct 
    FROM MyTable 
0

你可以嘗試這樣也。

FIDDLE

select count(*) total 
,count(p1.products)/count(*)*100 as currentlyused 
,count(p2.products)/count(*)*100 as used 
,count(p3.products)/count(*)*100 as not_sold 

from products p 
left join products p1 on p1.products=1 and p1.id=p.id 
left join products p2 on p2.products=0 and p2.id=p.id 
left join products p3 on p3.products=-1 and p3.id=p.id