Search code examples
sqlt-sqljoincreate-table

SQL Join 3 tables, add together duplicate rows


I'm having some trouble figuring this out.

"Choose all people and their orders, it's important that you show their name, id - the products name and the amount. If a person has made 2 orders with the same item, you want to only show 1 order, but add together the amounts from both orders."

This is what I have so far, but I can't wrap my head around how to get the multiple orders only show up as 1 with the amount being added together:

SELECT p.navn, p.id, v.varenavn, o.antal
FROM Vare as v
INNER JOIN Ordre as o
   ON v.vareid = o.v_id
INNER JOIN Person as p
   ON o.p_id = p.id

These are the tables:

Vare:

create table Vare(
    vareid int identity(1,1) primary key,
    nummer int,
    varenavn nvarchar(100),
    højde int,
    vægt int,
    pris money,
    dato nvarchar(20),
    datotil nvarchar(20),
)

Ordre:

create table Ordre(
    ordreid int identity(1,1) primary key,
    dato date,
    tid int,
    antal int,
    totalpris money,
    betalingsfrist date,
    rabatgruppe int,
    v_id int foreign key references Vare(vareid) not null,
    p_id int,
)

Person:

create table Person(
    id int identity(1,1) primary key,
    navn nvarchar(30),
    vejnavn nvarchar(50),
    postnr varchar(10),
    bynavn nvarchar(50),
    tlf int,
    kategori int,
)

Solution

  • You can try.

    sum all antal and group by orders.

    SELECT p.navn, p.id, v.varenavn, SUM(o.antal)
    FROM Vare as v
    INNER JOIN Ordre as o
       ON v.vareid = o.v_id
    INNER JOIN Person as p
       ON o.p_id = p.id
    GROUP BY 
        p.navn, p.id, v.varenavn