我有两个具有相同列的表。我想将这两个表连接到第三个表中,其中包含第一个表中的所有行和第二个表中所有具有相同位置的第一个表中不存在的日期的行。
例子:
交易:
date |location_code| product_code | quantity
------------+------------------+--------------+----------
2013-01-20 | ABC | 123 | -20
2013-01-23 | ABC | 123 | -13.158
2013-02-04 | BCD | 234 | -4.063
交易 2:
date |location_code| product_code | quantity
------------+------------------+--------------+----------
2013-01-20 | BDE | 123 | -30
2013-01-23 | DCF | 123 | -2
2013-02-05 | UXJ | 234 | -6
期望的结果:
date |location_code| product_code | quantity
------------+------------------+--------------+----------
2013-01-20 | ABC | 123 | -20
2013-01-23 | ABC | 123 | -13.158
2013-01-23 | DCF | 123 | -2
2013-02-04 | BCD | 234 | -4.063
2013-02-05 | UXJ | 234 | -6
我该怎么做?我试过这个:
SELECT date, location_code, product_code, type, quantity, location_type, updated_at
,period_start_date, period_end_date
INTO transactions_combined
FROM ( SELECT * FROM transactions_kitchen k
UNION ALL
SELECT *
FROM transactions_admin h
WHERE h.date NOT IN (SELECT k.date FROM k)
) AS t;
但这并没有考虑到我想包含具有相同日期但不同位置的行。我正在使用 Postgresql 9.2。
最佳答案
UNION
根本不会按照您的描述进行操作。这个查询应该:
CREATE TABLE AS
SELECT date, location_code, product_code, quantity
FROM transactions_kitchen k
UNION ALL
SELECT h.date, h.location_code, h.product_code, h.quantity
FROM transactions_admin h
LEFT JOIN transactions_kitchen k USING (location_code, date)
WHERE k.location_code IS NULL;
LEFT JOIN
/IS NULL
从第二个表中排除具有相同位置和日期的行。见:
使用 CREATE TABLE AS
而不是 SELECT INTO
。 The manual:
CREATE TABLE AS
is functionally similar toSELECT INTO
.CREATE TABLE AS
is the recommended syntax, since this form ofSELECT INTO
is not available in ECPG or PL/pgSQL, because they interpret theINTO
clause differently. Furthermore,CREATE TABLE AS
offers a superset of the functionality provided bySELECT INTO
.
或者,如果目标表已经存在:
INSERT INTO transactions_combined (<list names of target column here!>)
SELECT ...
旁白:我不会使用 date
作为列名。这是一个reserved word在每个 SQL 标准中以及在 Postgres 中的函数和数据类型名称。
关于sql - 将两个表组合成一个新表,以便忽略另一个表中的选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15559090/