The most elegant way would be to use the USING
clause in an explicit join condition:
SELECT houseid, v.vehid, v.epatmpg, d.houseid, d.trpmiles
FROM vehv2pub v
JOIN dayv2pub d USING (houseid)
WHERE v.vehid >= 1
AND d.trpmiles < 15;
This way, the column houseid
is in the result only once, even if you use SELECT *
.
Per documentation:
USING
is a shorthand notation: it takes a comma-separated list of
column names, which the joined tables must have in common, and forms a
join condition specifying equality of each of these pairs of columns.
Furthermore, the output of JOIN USING
has one column for each of the
equated pairs of input columns, followed by the remaining columns from each table.
To get the average epatmpg
for the selected rows:
SELECT avg(v.epatmpg) AS avg_epatmpg
FROM vehv2pub v
JOIN dayv2pub d USING (houseid)
WHERE v.vehid >= 1
AND d.trpmiles < 15;
If there are multiple matches in dayv2pub
, the derived table can hold multiple instances of each row in vehv2pub
after the join. avg()
is based on the derived table.