Hello everyone,
I have 3 tables, which are each 1:n.
an entry in table1 has n entries in table2, and so on.
lets call them cars, wheels, and screws for illustration. Screws can be clean(1) or rusty(2)
I am joining them together, because I want to count 2 things.
First, I want to have rows telling me how many good/bad screws per wheel I have for each car. So basically I am getting:
car_id wheel_id screw_state count(screws)
1 1 1 3
1 1 2 7
1 2 1 5
1 2 2 3
2 1 1 1
... and so on...
Now I want a second fact, namely how many rusty and clean screws I have for all wheels per car, without needing to know each specific number per wheel. So basically now I just leave off the GROUP BY over wheel_id, like this:
car_id screw_state count(screws)
1 1 8
1 2 10
2 1 1
... and so on...
The thing is, I would need both of them in one single query, because else I'd have a lot of sorting and rearranging to do. I believe the second, easier count over the total screws per car should be done as a subquery, but can I join the first, bigger query easily with a subquery?
How is this done? I would be happy over a quite specific answers, because I am not really an SQL wizard.
edit : I am working on an ORM, so funky thinks like below (hacking the col values to some constant) cant be done there easily. I have to get this solution working there, so JOIN/subquery/UNIONs without funky workarounds would be great.
Greetings, Tom