SQL如何计算组的相对值?

时间:2016-04-25 14:04:34

标签: sql postgresql group-by

假设我们销售汽车,我们想知道每个品牌销售的汽车数量。

数据:

car_id | brand | sold
----------------------
1      | BMW   | true
2      | BMW   | false
3      | Mazda | true
4      | Mazda | false
5      | Mazda | true

我们想得到的结果:

brand | sold
------------
BMW   | 50%
Mazda | 66%

怎么做(在PostgreSQL中)?

3 个答案:

答案 0 :(得分:2)

使用GROUP BY,然后使用COUNT语句将SUM除以CASE的真或假的组合。

假设已售出包含不是真实或错误的字符串。

SELECT brand, SUM(CASE WHEN sold = 'true' 
                       THEN 1 
                       ELSE 0 
                  END)/COUNT(*) AS Sold
FROM thedata
GROUP BY brand

输出

brand   Sold
BMW     0.5
Mazda   0.66

或者在SQL级别完成格式化。

SELECT brand, ROUND(SUM(CASE WHEN sold = 'true' 
                             THEN 1 
                             ELSE 0 
                        END)/COUNT(*))*100)|| '%' AS Sold
FROM thedata
GROUP BY brand

输出

brand   Sold
BMW     50%
Mazda   66%

答案 1 :(得分:1)

如果SUM()内是否已售出汽车,您可以使用CASE GROUP BY {/ 1}}:

Select  brand, 
        Sum(Case When sold = 'true' Then 1.00 Else 0.00 End) / Count(*) As sold
From    carTable
Group By brand

百分比为VARCHAR

Select  brand, 
        Convert(Varchar, 
            Sum(Case When sold = 'true' Then 1.00 Else 0.00 End) / Count(*)
            * 100) + '%' As sold
From    carTable
Group By brand

答案 2 :(得分:1)

ANSI SQL回答:

select brand, count(case when sold then 1 end)*100 / count(*)
from cars
group by brand

如果您想要50%而非50,请执行:

cast(count(case when sold then 1 end)*100 / count(*) as varchar(3)) || '%'