sql - 将两个表组合成一个新表,以便忽略另一个表中的选择行

标签 sql postgresql duplicates left-join union

我有两个具有相同列的表。我想将这两个表连接到第三个表中,其中包含第一个表中的所有行和第二个表中所有具有相同位置的第一个表中不存在的日期的行。

例子:

交易:

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 INTOThe manual:

CREATE TABLE AS is functionally similar to SELECT INTO. CREATE TABLE AS is the recommended syntax, since this form of SELECT INTO is not available in ECPG or PL/pgSQL, because they interpret the INTO clause differently. Furthermore, CREATE TABLE AS offers a superset of the functionality provided by SELECT 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/

相关文章:

sql - 在存储过程中使用 LIKE 和 IN/OR

sql - 如何从 Sql Server 中的 TimeZoneOffset 获知 TimeZone StandardName 或 DayLightName

sql - 需要有关 Merge 语句的帮助

sql - 多对多关系中的外键约束

sql - 查询滚动日期范围内不同值的计数

linq - 比较两个列表并返回不同的值和差异

c++ - 如何使存储在 vector 中的对象中的数据唯一?

SQL子字符串非贪婪正则表达式

sql - 每组值的自定义序列/自动增量

MySQL 按时间过滤数据库查询并查找重复项