简体   繁体   中英

Divide values from one column with corresponding values in another column

I have two columns person_type and time_in . I am trying to find the percentage of a person_type in each corresponding hour. My database looks like:

person_type || time_in
FT             N/A
FT             0
FT             4
FT             22
FT             23
NL             1
NL             2
NL             3
NL             4
NL             4

I am trying to create a query to return the following output:

% FT        || time_in
100            N/A
100            0
0              1
0              2
0              3
33             4
100            22
100            23

I have tried the following code:

select (
(select count(*) from delivery where person_type = 'FT')
/count(*)) as 'FT %', time_in
from delivery
group by hour
order by hour;

The issue here is my subquery returns 5 for every time_in value so my current output looks like:

% FT        || time_in
500            N/A
500            0
500            1
500            2
500            3
166            4
500            22
500            23

If I group by time_in in my subquery then I get an error message saying that the query is returning more than one value.

You can use conditional aggregation. For this purpose, I think that avg() is the simplest logic:

select time_in,
       avg( person_type = 'FT' ) * 100 as percent_ft
from delivery
group by time_in
order by time_in;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM