首页 > 解决方案 > 如何在 PostgreSql 中加入 2 个不重复值的表

问题描述

我正在使用以下方法加入两个表:

select table1.date, table1.item, table1.qty, table2.anotherQty 
from table1
INNER JOIN table2
on table1.date = table2.date

表格1

date   | item   | qty
july1  | itemA  | 20
july1  | itemB  | 30
july2  | itemA  | 20

表2

date   | anotherQty
july1  | 200
july2  | 300

预期结果应该是:

date   | item  | qty | anotherQty
july1  | itemA | 20  | 200
july1  | itemB | 30  | null or 0
july2  | itemA | 20  | 300

这样当我 sum(anotherQty) 时,它将只有 500,而不是:

date   | item  | qty | anotherQty
july1  | itemA | 20  | 200
july1  | itemB | 30  | 200
july2  | itemA | 20  | 300

即 200+200+300 = 700

标签: postgresqlduplicatesjointable

解决方案


试试下面的代码,但要知道,只要行间的 qty 值不同,你仍然会得到 'anotherQty' 字段分解成不同的值:

select 
    table1.date, 
    table1.item, 
    table1.qty, 
    SUM(table2.anotherQty)
from table1
INNER JOIN table2
    on table1.date = table2.date
GROUP BY
    table1.item, 
    table1.qty,
    table1.date

如果您需要它始终汇总到每个项目/日期的一行,那么您还需要将 a 添加SUM()到 table1.qty。或者,您可以为所需的每个数量运行一个公用表表达式(WITH()语句),在公用表表达式中对它们求和,然后将表达式重新加入您的最终 SELECT 语句。

编辑:

根据@Juan Carlos Oropeza 的评论,我不确定是否有办法table1.date在查询中包含 500 的总和值,因为您必须按日期对输出进行分组,这将导致聚合拆分成不同的线条。以下查询将在牺牲显示日期的情况下为您提供 anotherQty 的总和:

select  
    table1.item, 
    SUM(table1.qty), 
    SUM(table2.anotherQty)
from table1
INNER JOIN table2
    on table1.date = table2.date
GROUP BY
    table1.item 

如果您需要保留日期,则可以使用 WINDOW 函数显示总和,但请注意,这实际上是在进行运行求和,并且可能会丢弃您在此查询的输出中执行的任何后续求和后期处理:

select  
    table1.item,
    table1.date,
    SUM(table1.qty), 
    SUM(table2.anotherQty) OVER (Partition By table1.item) 
from table1
INNER JOIN table2
    on table1.date = table2.date
GROUP BY
    table1.item,
    table1.date,
    table2.anotherQty

推荐阅读