如果有如下两个表:
表一
day acount
1998-03-01 8
1998-03-04 9
1998-03-05 10
1998-03-09 8
表2
day bcount
1998-03-02 9
1998-03-03 7
1998-03-05 4
1998-03-06 3
select 查询是否可以按以下格式按升序返回数据?
结果
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
最佳答案
我建议使用 FULL OUTER JOIN 来连接 day
上的表获取结果的列:
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;
参见 SQL Fiddle with Demo . COALESCE
函数将返回第一个非空结果,因此可用于获取 day
同一列中的值,然后替换 nulls
在acount
和 bcount
列。
关于sql - SELECT 查询合并/加入 PostgreSQL 中的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860833/