简体   繁体   English

两个表的sql sum

[英]sql sum for two tables

I need help with some basic sql... here is the problem: In first table I have 我需要一些基本的SQL帮助...这里是问题:在第一个表我有

ID (primary key) 
data column (varchar) 

which contains products, in other I have 其中包含产品,其他我有

ID (primary) 
second ID (foreign key) //references to ID from first table
price (decimal 8,2)

What I need is to SUM price from second table that corresponds products from first table. 我需要的是从第二个表中的SUM价格对应第一个表中的产品。 also it should be saved as view. 它也应该保存为视图。 any help? 任何帮助?

JOIN the two tables, with GROUP BY and an aggregate function SUM like this: 使用GROUP BY和聚合函数SUM JOIN这两个表,如下所示:

CREATE VIEW DataPrices
AS
    SELECT 
      p.id,
      p.data,
      SUM(t.price) 
    FROM products p
    INNER JOIN secondtable t ON p.ID = t.ForeignKeyToTable1
    GROUP BY p.Id, p.data;
select table1.id, table1.data, sum(table2.price) as `total`
from   table1 inner join table2  
         on table1.id = table2.foreignkeyId
group  by table1.id, table1.data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM