天天看點

sql_每組占比問題

一張表有 group ,tablename,staragesize(存儲大小)幾個字段,

求出每組存儲大小占當比前80%的表,傳回group,tablename

select  
    a.group,
    a.tablename 
from
    table as a
join    
(    
select  
    group,
    sum(staragesize)*0.2 as sum_size20
from
    group    
group by group  
) as b
where a.group=b.group
having a.staragesize>a.sum_size20 ;      

求某張表裡的某個種類的占比問題

原來我寫的這樣,但是一直報錯

select
 space_id,status, sum_status/sum_id
from
(
select  
select space_id, status,count(*) as sum_status
from space_data_info 
where floor_num=11 and date_time 
between '2020-11-16 07:00:00' and '2020-11-20 21:00:00' and  module= 'comfort' 
group by space_id, status   
) a
join 
( 
select space_id, count(*) as sum_id
from space_data_info 
where floor_num=11 and date_time 
between '2020-11-16 07:00:00' and '2020-11-20 21:00:00' and  module= 'comfort' 
group by space_id  
) b
where a.space_id=b.space_id;      
sql_每組占比問題
select
 a.space_id,a.status,a.sum_status/b.sum_id
from
(
select space_id, status,count(*) as sum_status
from space_data_info 
where floor_num=11 and date_time 
between '2020-11-16 07:00:00' and '2020-11-16 21:00:00' and  module= 'comfort' 
group by space_id, status   
) a
join 
( 
select space_id, count(*) as sum_id
from space_data_info 
where floor_num=11 and date_time 
between '2020-11-16 07:00:00' and '2020-11-20 21:00:00' and  module= 'comfort' 
group by space_id  
) b
where a.space_id=b.space_id;