2022-03-27

Sum duplicated rows in SQL Server

Sum repeated values in datatable (VB.NET) or in SQL Server (are better one or other solutions)

I have a database in which are reported repeated rows:

Description | Price | Q.ty | Tax
AAAAAAAAAAA | 10.00 | 20.0 | 5
AAAAAAAAAAA | 10.00 | 12.0 | 5
BBBBBBBBBBB | 18.00 | 09.0 | 5
BBBBBBBBBBB | 18.00 | 12.0 | 5
CCCCCCCCCCC | 13.00 | 15.0 | 5
AAAAAAAAAAA | 17.0  | 19.0 | 5

And I want obtain something like this:

Description | Price | Q.ty | Tax
AAAAAAAAAAA | 10.00 | 51.0 | 5
BBBBBBBBBBB | 18.00 | 21.0 | 5
CCCCCCCCCCC | 13.00 | 15.0 | 5

I've created a datatable in VB.NET and I tried to sum values in it, and then show summed rows in a datagridview, but without results. Then, I've tried to do this with SQL Server (2019), without results again.

Can someone help me, please?

My code is:

Dim conn as New SqlConnection("*****")
Dim cmd2 As New SqlCommand("SELECT Description, Price, SUM(Q.ty), Tax, FROM Prodotti GROUP BY Descrizione", conn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd2
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.SuspendLayout()
DataGridView1.DataSource = dt
DataGridView1.ResumeLayout()
conn.Close()

I want to obtain my goal with VB.NET or directly with SQL Server.



No comments:

Post a Comment