简体   繁体   中英

Combine the pivot table to calculate the ratio

On SQL, I have a pivot table like:

col1 col2 col3
A     0    90
A     1    10
B     0    80
B     1    20

I want to have the following:

col1 ratio
A     90% 
B     80%

The only way that comes to my mind is to calculate the sum of 1s and 0s per col1 values. Then divide the amount of 1s to total count but that requires additional subqueries. Maybe there is an alternative option to this?

Use aggregation and arithmetic. Assuming 0 / 1 values in the second column:

select col1, sum(col2 * col3) / sum(col3)
from t
group by col1;

Some databases do integer division, so if the columns are integers, you might want:

select col1, sum(col2 * col3) * 1.0 / sum(col3)

Then, you don't need to use the derived table. You could go to the base table and aggregate using a formula:

select col1, avg(col3 * 1.0)
from base
group by col1

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