简体   繁体   中英

How can I sum data from mulitple rows which have the same foreign key into one row?

I have two tables which have a 1 to n relation. One table contains general Information of a bill (named bill) (< -1 to n ->) and the other contains Items which are on the bill (named items). I want a query that Lists all Bills and sums up the prices from the items in a new row. But of course i want every Bill listed just once not for every item.

Usually i don't post anything. But i can't find an answer because i don't know how to search for this problem. Sorry when this is obvious.

What my tables look like:

bill:
bill_id - customer - date

items:
item_id - bill_id - amount - price

A simple join with aggregation should work here:

SELECT
    b.bill_id,
    COALESCE(SUM(i.price), 0) AS total_price
FROM bill b
LEFT JOIN items i
    ON b.bill_id = i.bill_id
GROUP BY
    b.bill_id;

If you want to include the other two columns from the bill table, then just add them to the SELECT and GROUP BY clauses.

You may try this.

   ; with cte as (
   select b.bill_id, i.item_id ,isnull(i.price,0) as Price from
   Bill as b inner join items as i on b.bill_id =i.bill_id 
   union all
   select b.bill_id , null,  sum(isnull(i.price,0)) from
   Bill as b inner join items as i on b.bill_id =i.bill_id 
   group by b.bill_id 
   )
   select * from cte order by bill_id, item_id desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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