【问题标题】:How to find the SUM (product_price) from the combination of two tables using JOIN in SQL如何在 SQL 中使用 JOIN 从两个表的组合中找到 SUM (product_price)
【发布时间】:2021-02-03 08:07:36
【问题描述】:

我有两张桌子:

表 A

发票日期 |客户 ID |装运编号 |重量 |产品价格

表 B

发票日期 |客户 ID |装运编号 |重量

我正在尝试创建一个新表 C,它使用 sum(product_price) 计算一个新列: 所以我期待类似的东西: (每个客户可以有许多具有相同shipping_id但product_price发生变化的货物 对于每个不同的 shipping_id ) (表 B 中缺少一些权重)

示例: 表 A

invoicedate | client_id | shipment_id | weight | product_price  
12/10/19         1111        888           48        36            
13/11/19         2222        111           30        45
12/10/19         1111        888           48        125         
12/10/19         1111        888           48        127.2

表 B

invoicedate | client_id | shipment_id | weight 
12/10/19         1111        888           48                    
13/11/19         2222        111           30       
12/10/19         1111        888           -                  
12/10/19         1111        888           48

新表 C

distinct(client_id)|invoicedate |  distinct(weight) | total_sum(product_price)

    1111           |   12/10/19 |       1111        |    (36+125+127.2)                   
    2222           |   13/11/19 |      2222         |        45      

我的代码:

    create table C as 
    select A.invoicedate,A.shipment_id,A.weight,sum(A.product_price) as sum_product_price
    from A
    right join B on B.id=A.id
    group by  A.id, A.weight

sum(product_price) 计算错误,我不明白为什么..

【问题讨论】:

  • 请解释distinct(weight)。另外,标记您正在使用的数据库。
  • 任何表中都没有列id。您是否尝试过在没有 SUM 的情况下运行查询来检查行中的产品价格?您是否需要执行 JOIN,因为您只从 A 表中选择列?

标签: sql join sum right-join


【解决方案1】:
select A.client_id,A.invoicedate,A.weight,SUM(product_price)  from Table_A A
group by A.client_id,A.invoicedate ,A.weight 

【讨论】:

    【解决方案2】:

    如果你想通过编译两个表来创建一个表。因此,本参考资料将对您有所帮助。

    使用另一个表创建表

    也可以使用CREATE TABLE 创建现有表的副本。

    以下 SQL 创建一个名为“TestTables”的新表(它是“Customers”表的副本):

    示例

    CREATE TABLE TestTable AS
    SELECT customername, contactname
    FROM customers;
    

    所以,在我按照说明尝试后,我自己尝试了,我得到了什么

    创建'C' 表:

    create table C AS
    SELECT A.client_id as distinct(client_id), A.invoicedate, B.weight AS distinct(weight), SUM(product_price) AS total_sum(product_price)
    FROM A, B
    FULL OUTER JOIN A.client_id = B.client_id
    group by A.client_id, B.invoicedate;
    

    选择语句:

    SELECT * FROM C;

    输出

    distinct(client_id)|invoicedate |  distinct(weight) | total_sum(product_price)
    
        1111           |   12/10/19 |       1111        |       133                
        2222           |   13/11/19 |       2222        |       133    
    

    参考: SQL TABLE Keyword

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2020-04-19
      • 2017-05-03
      • 2019-06-13
      • 2020-09-02
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多