Skip to content
Advertisement

Combining Data from Multiple Rows in Simple Database

I am new to using SQL. I have constructed the following simple database, which has the ID of music albums and the number of copies bought.

enter image description here

In the album_ID column, there are two pieces of data with ID 1. They have quantity_bought values of 10 and 4. Is it possible to combine these two rows into one row which has ID 1 and a total quantity_bought value of 14?

Advertisement

Answer

WITH
-- your input
sold(album_id,qty_bought) AS (
          SELECT 1,10
UNION ALL SELECT 2, 5
UNION ALL SELECT 1, 4
)
SELECT
  album_id
, SUM(qty_bought) AS quantity_bought
FROM sold
GROUP BY album_id;
album_id|quantity_bought
       1|             14
       2|              5
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement