Skip to content
Advertisement

SQL Query for joining equivalent rows summing a column

I have two tables, articolo and saldo.

articolo is like this:

id desc_breve variante taglia
338673 ANYT229 00109 XL
338674 ANYT229 00109 XL
338675 ANYT229 00109 XXL
338711 MYP506S 00002 56
338712 MYP506S 00002 58
338713 MYP506S 00002 60
338714 MYP506S 00002 60
338715 MYP506S 00002 62

saldo (omitting the primary key id) is like this:

id_articolo giacenza
338673 12.0000
338674 13.0000
338675 23.0000
338711 2.0000
338712 5.0000
338713 1.0000
338714 8.0000
338715 8.0000

I need to join the two tables from the id field in articolo and the id_articolo field in saldo with a query that returns desc_breve, variante, taglia and giacenza.

The problem is that some rows in the first table have the same desc_breve, variante and taglia, and in that case I have to join them in a single row and SUM their respective giacenza field in the saldo table.

Is it possible to do a query for that? I’m using Microsoft SQL Server.

Advertisement

Answer

You seem to be describing a join with group by:

select a.desc_breve, a.variante, a.taglia, sum(s.giacenza)
from articolo a join
     saldo s
     on s.id_articolo = a.id
group by a.desc_breve, a.variante, a.taglia;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement