I have this table structure:
TABLE: PERSON TABLE: CAR
PersonID PersonID | CarID
------ ---------|---------
1 1 | 51
1 | 52
TABLE: PET TABLE: AGE
PersonID | PetID Person | AgeID
---------|---- -------|----
1 | 81 1 | 20
1 | 82
1 | 81
One person can have many cars and pets, but only one age.
I want to calculate the number of cars that someone has, to count the number of pets and indicate their age.
This is what I still have:
select
car.personid as person,
count(car.carid) as cars,
null as pets
from car
where car.personid = 1
group by car.personid
union all
select
pet.personid as person,
null as cars,
count(pet.petid) as pets
from pet
where pet.personid = 1
group by pet.personid
This gives:
Person | Cars | Pets
-------|------|-----
1 | 2 | null
1 | null | 3
But I would like the results to look like this:
Person | Cars | Pets | Age
-------|------|------|----
1 | 2 | 3 | 20
There is a fiddle here: http://sqlfiddle.com/#!3/f584a/1/0
I am completely obsessed with how to wrap records in a single row and add age columns.
drc15 source
share