以下SQL查询:
SELECT
SUM(aol_int) AS AOL,
SUM(android_phone_int) AS Android_Phone,
SUM(androidTablet_int) AS Android_Tablet
FROM mytable;
在AOL,Android_Phone和Android_Tablet列下给我总值
但是,我试图获得AOL,Android_Phone和Android_Tablet的百分比,因此我决定按如下方式编写上述查询:
SELECT
SUM(CASE WHEN 'aol_int' THEN 100 END) / Count(aol_int) AS AOL,
SUM(CASE WHEN ‘android_phone_int’ THEN 100 END) /Count(android_phone_int) AS Android_Phone,
SUM(CASE WHEN ‘androidTablet_int’ THEN 100 END)/Count(androidTablet_int) AS Android_Tablet
FROM mytable;
我在每列中都得到NULL。我在这里做错了什么?
答案 0 :(得分:0)
如果这3个加起来达到100%,那么你可以将每个总和除以总和来得到百分比。我认为你想要看到20%为“20.00”而不是“0.2”,所以在我的例子中,我会将比率乘以100并以小数精度2对其进行四舍五入,但对你来说很容易根据你的需要改变那些。
select
round((sum(aol_int) /
(sum(aol_int + android_phone_int + androidtablet_int))) *
100,2) as aol_percentage,
round((sum(android_phone_int) /
(sum(aol_int + android_phone_int + androidtablet_int))) *
100,2) as android_phone_percentage,
round((sum(androidtablet_int) /
(sum(aol_int + android_phone_int + androidtablet_int))) *
100,2) as android_tablet_percentage
from mytable