开发者

Oracle SQL: Add sum from another table to query results

I have two tables where one of the tables, TABLE2, has a column for TABLE1_IDs, thus there is a many-to-one relationship between TABLE2 and TABLE1 rows. TABLE2 has a column PRICE which is a number that represents a dollar amount. I have a query that obtains certain rows of TABLE1, but I want to get the total of all corresponding TABLE2 rows' PRICE values as an additional column in the query results.

How do I accomplish this in 开发者_运维知识库Oracle?


Easy - join, and sum.

select t1.table1_id
,      sum(t2.price) total_price
from   table1 t1
,      table2 t2
where  t1.table1_id = t2.table1_id
group  by t1.table1_id;


I believe you want something like this:

SELECT A.Id, SUM(B.Price) TotalPrice
FROM (  SELECT *
        FROM Table1
        WHERE Something) A
LEFT JOIN Table2 B
ON A.Id = B.Table1_id
GROUP BY A.Id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜