如何将具有相同列的两个 table 转换为一个添加计数并按第三个 table 分组

How to convert two tables with same columns to one adding count and groupping by third table

我有两个具有相同列的 table:它们的产品和价格。

Table1:

table 1:

Product   Price
---------------
name1      1
name2      3
name3      4
name1      2

Table 2:

Product   Price
---------------
name1      1
name3      2
name4      5
name3      3

我还有 table 只有产品:

Table 3:

Product
--------
name1
name2
name3
name4

我想从按产品名称分别分组的每个 table 中取出相同产品的价格和数量的总和。

我尝试使用 join 和 union 来生成 table,但我所拥有的只是 table 和单个值,或者生成正确的 table 但结果错误,就像结果翻倍一样。

select t3.product as _product, sum(t1.price) as _t1Sum, count(t1.price) as _t1Count, sum(t2.price) as _t2Sum, count(t2.price) as _t2Count
from Table3 as t3,
     Table1 as t1 
  full join Table2 as t2 on t1.product = t2.product
where (t3.product = t1.product or t3.product = t2.product)
group by _product

使用 unionunion all 我得到了包含 3 列的 table。 使用任何类型的连接,我得到 table 5 列和重复结果,就像两列中都有 3 个 name3 产品一样 Table_Sum.

结果示例table我想要:

Product     Table1_Sum    Table1_Amount   Table2_Sum  Table2_Amount
-------------------------------------------------------------------
name1         3               2             1            1
name2         3               1             0            0
name3         4               1             5            2
name4         0               0             5            1

如何编辑我的查询以使 table 像示例一样?

demo:db<>fiddle


1.方式:可以使用相关子查询:

SELECT
    p.product,
    (SELECT COALESCE(SUM(price), 0) FROM table1 t1 WHERE t1.product = p.product),
    (SELECT COUNT(*) FROM table1 t1 WHERE t1.product = p.product),
    (SELECT COALESCE(SUM(price), 0) FROM table2 t2 WHERE t2.product = p.product),
    (SELECT COUNT(*) FROM table2 t2 WHERE t2.product = p.product)
FROM
    products p

2。方式:加入前可以分组:

SELECT
    p.product,
    COALESCE(t1.sum, 0) AS t1_sum,
    COALESCE(t1.count, 0) AS t1_cnt,
    COALESCE(t2.sum, 0) AS t2_sum,
    COALESCE(t2.count, 0) AS t2_cnt
FROM
    products p
LEFT JOIN 
    (SELECT product, SUM(price), COUNT(*) FROM table1 GROUP BY product) t1
    ON t1.product = p.product
LEFT JOIN 
    (SELECT product,SUM(price), COUNT(*) FROM table2 GROUP BY product) t2
    ON t2.product = p.product

如果有none,COALESCE()函数将结果设置为0