查找针对总客户的产品百分比

时间:2012-09-10 15:22:50

标签: sql sql-server select percentage

我的sql表有2列userid和产品,userid是唯一的,而产品有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

4 个答案:

答案 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 

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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