使用同一列中的数据计算SQL语句所占的百分比

时间:2019-06-13 07:05:24

标签: mysql sql percentage

我正在尝试计算百分比。计算公式应如下:

  

%= {Totale time AAN /(Totale time AAN +总时间UIT))* 100

表如下:

+------------+-------------+
| DATA_SOORT | DATA_WAARDE |
+------------+-------------+
| TEMP       |          22 |
| AAN        |       14200 |
| UIT        |       10200 |
| HUM        |          44 |
| AAN        |       10000 |
| UIT        |       13000 |
| TEMP       |          23 |
+------------+-------------+

来自AAN和UIT的DATA_WAARDE以毫秒为单位。

我尝试过:

     SELECT sum((((`DATA_WAARDE`/1000) 
     FROM `IOT_DATA` 
     WHERE `DATA_SOORT`="AAN")/sum(`DATA_WAARDE`/1000) 
     FROM `IOT_DATA` 
     WHERE (`DATA_SOORT`="UIT" OR `DATA_SOORT`="AAN"))*100)

上表中的预期结果应为51,05%。

4 个答案:

答案 0 :(得分:0)

只需使用case when,如下所示的SQL:

select * from iot_data;
 data_soort | data_waarde 
------------+-------------
 TEMP       |          22
 AAN        |       14200
 UIT        |       10200
 HUM        |          44
 AAN        |       10000
 UIT        |       13000
(6 rows)

 select
     concat(round(sum(case when data_soort='AAN' then data_waarde else null end)*100.0/sum(case when data_soort in ('AAN','UIT') then data_waarde else null end),2),'%') as percent
 from
     iot_data;
+---------+
| percent |
+---------+
| 51.05%  |
+---------+
1 row in set (0.02 sec)

答案 1 :(得分:0)

尝试:

select `DATA_WAARDE`*100/SUM(`DATA_WAARDE`) OVER(PARTITION BY 1) from `IOT_DATA` WHERE (`DATA_SOORT`="UIT" OR `DATA_SOORT`="AAN")

您还可以将其封装到另一个仅返回AAN的查询中

答案 2 :(得分:0)

SELECT SUM(IF(DATA_SOORT='AAN', `DATA_WAARDE`, NULL))
/ SUM(`DATA_WAARDE`) * 100
FROM `IOT_DATA` 
WHERE `DATA_SOORT` IN ('UIT', 'AAN')

答案 3 :(得分:0)

我喜欢使用avg()

select avg( data_waarde = 'ANN') * 100 as percent
from iot_data
where data_soort in ('UIT', 'AAN');