postgresql 如何合并两个结果

nle07wnf  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(160)

我有3张table购买,空中转移和海上转移。我在db fiddle中做了示例代码。我的问题是在第6段,我没有任何海上转移,我得到空的身份证,这是因为我使用的身份证从海上转移。我该怎么做才能解决这个问题?
购买表:

CREATE TABLE purchase
(
id SERIAL PRIMARY KEY,
date DATE NOT NULL
)

空气输送台:

CREATE TABLE air_transfers
(
id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL REFERENCES purchase(id),
units INTEGER NOT NULL
)

海上转移表:

CREATE TABLE sea_transfers
(
id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL REFERENCES purchase(id),
units INTEGER NOT NULL
)

我的外部连接:

WITH sea_transfers AS (
SELECT purchase_id, SUM(units) AS units
FROM sea_transfers
GROUP BY purchase_id
),
air_transfers AS (
SELECT purchase_id, SUM(units) AS units
FROM air_transfers
GROUP BY purchase_id
)
SELECT st.purchase_id, (COALESCE(st.units,0) + COALESCE(at.units,0)) AS units
FROM sea_transfers AS st
FULL OUTER JOIN air_transfers AS at
ON st.purchase_id = at.purchase_id

如果我的海运费是空的,我得到这样的结果:

relj7zay

relj7zay1#

你可以做

SELECT COALESCE(st.purchase_id, at.purchase_id) as purchase_id

Fiddle

第三方编辑

关于sqlitetutorial.net
COALESCE函数接受两个或多个参数,并返回第一个非空参数。下面说明了COALESCE函数的语法:

SELECT COALESCE(10,20); -- return 10
SELECT COALESCE(NULL,20,10); -- returns 20

从官方sqlite文档

coalesce(X,Y,.)

coalesce()函数返回第一个非NULL参数的副本,如果所有参数都是NULL,则返回> NULL。Coalesce()必须至少有2个参数。

e1xvtsh3

e1xvtsh32#

我认为你正在寻找UNION ALL而不是FULL OUTER JOIN,因为UNION ALL将合并两个结果air_transferssea_transfers表,你将得到所有的purchase_idunits值从两个表。

SELECT  purchase_id, SUM(units) AS units
FROM (
   SELECT purchase_id,units FROM air_transfers
   UNION ALL
   SELECT purchase_id,units FROM sea_transfers
) t1
GROUP BY purchase_id

相关问题