我正在使用Postgresql,我创建了两个返回结果的子查询,如下所示:
firm_id type_1 fee_1
1 2 100
2 4 300
5 1 100
firm_id type_2 fee_2
1 3 200
2 3 200
3 2 150
4 5 300
我想得到一个结果:
firm_id type_1 type_2 total_fee
1 2 3 300
2 4 3 500
3 0 2 150
4 0 5 300
5 1 0 100
任何帮助表示赞赏!
答案 0 :(得分:2)
使用FULL JOIN
和coalesce()
:
with q1(firm_id, type_1, fee_1) as (
values
(1, 2, 100),
(2, 4, 300),
(5, 1, 100)),
q2 (firm_id, type_2, fee_2) as (
values
(1, 3, 200),
(2, 3, 200),
(3, 2, 150),
(4, 5, 300))
select
firm_id,
coalesce(type_1, 0) type_1,
coalesce(type_2, 0) type_2,
coalesce(fee_1, 0)+ coalesce(fee_2, 0) total_fee
from q1
full join q2
using (firm_id);
firm_id | type_1 | type_2 | total_fee
---------+--------+--------+-----------
1 | 2 | 3 | 300
2 | 4 | 3 | 500
3 | 0 | 2 | 150
4 | 0 | 5 | 300
5 | 1 | 0 | 100
(5 rows)
答案 1 :(得分:1)
SELECT firm_id
,coalesce(t.type_1, 0) type_1
,coalesce(b.type_1, 0) type_2
,coalesce(t.fee_1, 0) + coalesce(b.fee_1, 0) total_fee
FROM (
SELECT * --Your first select query
FROM tablea
) t
FULL JOIN (
SELECT * --Your second select query
FROM tableb
) b using (firm_id)
FULL JOIN
:结合左外连接和右外连接的结果。
连接表将包含两个表中的所有记录,并为任何一方的缺失匹配填写NULL。
COALESCE
函数返回其第一个非null的参数。仅当所有参数都为null时才返回Null。当检索数据用于显示时,它通常用于替换默认值为空值
答案 2 :(得分:1)
SELECT coalesce( t1."firm_id", t2."firm_id" ) as firm_id,
coalesce( t1."type_1", 0 ) as type_1,
coalesce( t2."type_2", 0 ) as type_2,
coalesce( t1."fee_1", 0 )
+
coalesce( t2."fee_2", 0 ) as total_fee
FROM table1 t1
FULL JOIN table2 t2
ON t1."firm_id" = t2."firm_id"
其中table1和table2必须由子查询替换
看演示:http://sqlfiddle.com/#!15/6d391/2
答案 3 :(得分:0)
select coalesce(sq1.firm_id, sq2.firm_id) as firm_id, coalesce(type_1, 0), coalesce(type_2, 0), coalesce(fee_1, 0)+coalesce(fee_2, 0) as total_fee
from <subquery1> as sq1
outer join <subquery1> as sq1
on sq1.firm_id=sq2.firm_id
答案 4 :(得分:0)
如果您有两个子查询,例如a和b,它们为您设置A并设置B,那么您要查找的是完全连接A x B,其中完整连接中的至少一个firm_id不为空,计算列total_fee = fee_1 + fee_2。
我对postgresql语法并不熟悉,但它应该像
select
-- get rid of the columns you don't want
a.firm_id, a.type_1, a.type_2, a.fee_1,
b.firm_id, b.type_1, b.type_2, b.fee_2,
a.fee_1 + b.fee_2 as total_fee
from ( subquery_1 here ) as a
full join ( subquery_2 here) as b
on
b.firm_id = a.firm_id and
b.type_1 <> a.type_1
where
a.firm_id is not null or b.firm_id is not null