'Query to calculate the proportion [duplicate]
I am new to SQL (using SQLiteStudio) and I wrote such a query to calculate Proportion for each group ( number of rooms) from the total sale of apartments. But it doesn't calculate correctly. Give a result of 100 for each group. I don't know what I'm doing wrong can you guys help in any way? Thanks!
1. SELECT
2.l.num_rooms as "Number",
3.count(l.id_locale) as "Number sales",
4.round(count (l.id_locale)/
5.(SELECT count (l.type_locale)FROM locale
6.WHERE l.type_locale = 'Appartement' )*100,2) as "Proportion"
7.FROM locale l
8.WHERE l.type_locale = 'Appartement'
9.GROUP BY l.num_rooms
10.ORDER BY l.num_rooms;
| type_locale | surface | num_rooms | fk_lieu | id_locale |
|---|---|---|---|---|
| Appartement | 52 | 1 | 45 | 1 |
| Appartement | 45 | 2 | 67 | 21 |
| Appartement | 12 | 3 | 34 | 78 |
| Appartement | 67 | 2 | 89 | 12 |
| Appartement | 31 | 1 | 15 | 56 |
Solution 1:[1]
I see two problems in your code: 1) You are using and integer division (2/5 = 0); 2) the subquery is a correlated one while it should be unrelated to a main query. So use another alias in the subquery and convert at least one of the arguments in the expression to real.
SELECT l.num_rooms as "Number",
count(l.id_locale) as "Number sales",
round(count(l.id_locale)*1.0 /
(SELECT count(l2.id_locale) FROM locale l2
WHERE l2.type_locale = 'Appartement' )*100,2) as "Proportion"
FROM locale l
WHERE l.type_locale = 'Appartement'
GROUP BY l.num_rooms
ORDER BY l.num_rooms;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serg |
