如何在存储过程中获得百分比

时间:2016-10-19 11:12:15

标签: mysql database stored-procedures

我有存储过程,其中我通过计数获得类别存在。我想要它的总百分比。样本是我的总价值。我需要样品中是或否的百分比。请帮忙。我的存储过程如下。

BEGIN

SELECT 

    SC.name as SC,
    SUM(IF(is_category_present = 1, 1, 0)) as YES,
    SUM(IF(is_category_present = 0, 1, 0)) as NO,
    COUNT(OC.outlet_id) as SAMPLE

FROM outlet_categories OC
INNER JOIN outlets O on O.id = OC.outlet_id
INNER JOIN sale_channels SC on SC.id = O.sale_channel_id

WHERE OC.month = month
AND CASE WHEN location_type = 1 THEN OC.zone_id = location
         WHEN location_type = 2 THEN OC.state_id = location
         WHEN location_type = 3 THEN OC.city_id = location

    END
AND OC.category_id = category_id

GROUP BY SC.id;

END

BEGIN SELECT SC.name as SC, SUM(IF(is_category_present = 1, 1, 0)) as YES, SUM(IF(is_category_present = 0, 1, 0)) as NO, COUNT(OC.outlet_id) as SAMPLE FROM outlet_categories OC INNER JOIN outlets O on O.id = OC.outlet_id INNER JOIN sale_channels SC on SC.id = O.sale_channel_id WHERE OC.month = month AND CASE WHEN location_type = 1 THEN OC.zone_id = location WHEN location_type = 2 THEN OC.state_id = location WHEN location_type = 3 THEN OC.city_id = location END AND OC.category_id = category_id GROUP BY SC.id; END

1 个答案:

答案 0 :(得分:1)

简单计算应该有效:

(SUM(IF(is_category_present = 1, 1, 0))*1.0) / COUNT(OC.outlet_id) * 100.0 AS perc_yes
(SUM(IF(is_category_present = 0, 1, 0))*1.0) / COUNT(OC.outlet_id) * 100.0 AS perc_no