I have data that looks like this:
State Sex ---- --- GA M GA M GA F GA F GA F NY M NY M NY M NY M NY F NY F NY F NY F NY F
I want the result to be:
- one row per state
- col1 State
- col2 count of Males
- col3 count of Females
- col4 total count by state
- col 5 percent Male by state
The query I am using is:
select t.state State, M.count Male, F.count Female, count(t.state) Total, CONCAT(ROUND(CAST(M.count as float)/CAST(count(t.state) as float)*100, 2), '%') as calc from MyTable t join ( select state, count(sex) as count from MyTable where sex ='M' group by state) M on t.state = M.state join ( select state, count(sex) as count from MyTable where sex ='F' group by state) F ON M.state = F.state group by t.state, m.count, F.count;
The above query works but I am wondering if I did this in the most effecent way. This was done using SQLServer but I think this should be the same for all RDBMS. The link is here: http://sqlfiddle.com/#!18/7a969/87
https://stackoverflow.com/questions/66739812/query-with-multiple-subqueries-efficiency March 22, 2021 at 11:04AM
没有评论:
发表评论