Question

If there are two tables as mentioned below:

Table 1

    day          acount
    1998-03-01     8
    1998-03-04     9
    1998-03-05     10
    1998-03-09     8

Table 2

    day          bcount
    1998-03-02     9
    1998-03-03     7
    1998-03-05     4
    1998-03-06     3

Can a select query return the data in ascending order in the format below?

Result

    day          acount        bcount
    1998-03-01     8             0
    1998-03-02     0             9
    1998-03-03     0             7
    1998-03-04     9             0
    1998-03-05     10            4
    1998-03-06     3             0
    1998-03-09     8             0
Was it helpful?

Solution

I would suggest using a FULL OUTER JOIN to join the tables on the day column to get the result:

select coalesce(t1.day, t2.day) "day",
  coalesce(t1.acount, 0) acount,
  coalesce(t2.bcount, 0) bcount
from table1 t1
full outer join table2 t2
  on t1.day = t2.day;

See SQL Fiddle with Demo. The COALESCE function will return the first non-null result, so this can be used to get the day values in the same column and then replace the nulls in the acount and bcount columns.

OTHER TIPS

@bluefeet's query is the way to go. Only adding some syntactical sugar and corrective:

SELECT day
     , coalesce(t1.acount, 0) AS acount
     , coalesce(t2.bcount, 0) AS bcount
FROM      table1 t1
FULL JOIN table2 t2 USING (day)

SQL Fiddle.

  • If you use the shorter USING clause for the JOIN condition (possible in this case), you also don't need coalesce(t1.day, t2.day), since this is exactly what day without table qualification resolves to after being listed in the USING clause.

  • While it is ok to skip the key word AS for table aliases, you should never skip it for column aliases - as documented in the manual in a separate paragraph Omitting the AS Key Word:

In FROM items, both the standard and PostgreSQL allow AS to be omitted before an alias that is an unreserved keyword. But this is impractical for output column names, because of syntactic ambiguities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top