I’m having an Idiot Day today. I’m sure this is relatively simple, but my brain just isn’t giving me the answer.
I have a table whose rows are types of object. Looks something like this:
id name foo bar house_id
1 Cat 12 4 1
2 Cat 9 4 2
3 Dog 8 23 1
4 Bird 9 54 1
5 Bird 78 2 2
6 Bird 29 32 3
This isn’t how I’d choose to implement it, but it’s what I’m working with. Objects (cats, dogs and birds, in real life they’re actual business things) have been added to the table on an ad-hoc basis. When house_id 1 needs cats in it, a record for cats gets put in. When house_id 3 gets dogs, a record gets put in for dogs.
I now need to update this table so every type of object (Cat, Dog, Bird) has a record for a given house_id. I want to do this by inserting the result from a select query that returns a single record for each type, with the earliest values for ‘foo’ and ‘bar’ from a row of that type, if and only if there is no existent record for that type with the given house_id.
So for the above example data, where the given house_id = 3, the select query would return the following:
name foo bar house_id
Cat 12 4 3
Dog 8 23 3
which I can then insert straight into the table.
Basically, return the first row of each distinct name if there are no rows of that name with a given house_id.
Suggestions welcome. DB engine is postgres if that helps.
Result: