Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 SQL Query Help, summing rows

Author  Topic 

eazyc10
Starting Member

1 Post

Posted - 2005-12-16 : 14:06:06
Hi,

I have a SQL query question.

I am trying to take data from a table, and sum of the qty's for each unique item.

It would look something like this:

item qty
A 2
A 3
B 1
C 2
B 4
A 2
C 1
B 1

And I would like to query this and put it into a new table as follows:

item qty
A 7
B 6
C 3

In essence summing the qty for each unique item.

Is this possible through just plan SQL or do I need to look into some more programming?

Thanks

Srinika
Master Smack Fu Yak Hacker

1378 Posts

Posted - 2005-12-16 : 14:39:59
Insert Into NewTable
Select Item, sum(qty) from OldTbl group by Item

Advice: Read about aggregate functions, group by ...
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2005-12-16 : 14:56:48
[code]
USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99(item char(1), qty int)
GO

INSERT INTO myTable99(item, qty)
SELECT 'A', 2 UNION ALL
SELECT 'A', 3 UNION ALL
SELECT 'B', 1 UNION ALL
SELECT 'C', 2 UNION ALL
SELECT 'B', 4 UNION ALL
SELECT 'A', 2 UNION ALL
SELECT 'C', 1 UNION ALL
SELECT 'B', 1
GO

SELECT * FROM myTable99
GO

SELECT item, SUM(qty) AS SUM_qty INTO myNewTable99 FROM myTable99 GROUP BY item
GO

SELECT * FROM myNewTable99
GO

DROP TABLE myTable99, myNewTable99
GO

[/code]


Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-12-19 : 01:16:05
Why is myNewTable99 needed?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2005-12-19 : 01:42:28
quote:
Originally posted by madhivanan

Why is myNewTable99 needed?

Madhivanan

Failing to plan is Planning to fail


quote:
And I would like to query this and put it into a new table


-----------------
[KH]

Learn something new everyday
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-12-19 : 02:10:58
Well. I didnt read question fully

>>I would like to query this and put it into a new table as follows:

Why do you need seperate table?
You can just use Select Statement

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -