user9646393
user9646393

Reputation: 1

SQL Grouping to show sum

I Have below data returned from my code :

Part        QTYPerUnit   Multiplier
PN1         8            1
PN1         72           2
PN1         40           3
PN1         16           4
PN1         24           6

I need the results in new table to be grouped in 1 row and show the total:

Part        QTYPerUnit   Multiplier
PN1         160          16

Upvotes: 0

Views: 26

Answers (1)

PSK
PSK

Reputation: 17943

Simply putting following query for the given data will give you desired output

SELECT SUM([QTYPerUnit]) QTYPerUnit, SUM([Multiplier]) Multiplier FROM [TABLE_NAME]

If you have multiple parts, you can use GROUP BY [Part] like following.

SELECT [Part], SUM([QTYPerUnit]) QTYPerUnit, SUM([Multiplier]) Multiplier 
FROM [TABLE_NAME]
GROUP BY [Part]

To insert into a new table, you can do it in following way.

INSERT INTO [NEW_TABLE]([Part],[QTYPerUnit],[Multiplier])
SELECT [Part],SUM([QTYPerUnit]), SUM([Multiplier]) 
FROM [TABLE_NAME]
GROUP BY [Part]

Or simpally

SELECT [Part],SUM([QTYPerUnit]) QTYPerUnit, SUM([Multiplier]) Multiplier 
INTO [NEW_TABLE]
FROM [TABLE_NAME]
GROUP BY [Part]

Above statement will crate a new table and will insert the values. It will throw error if the table already exists.

DEMO

Upvotes: 1

Related Questions