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
 Transact-SQL (2000)
 How to select SUM from another table

Author  Topic 

chexone
Starting Member

6 Posts

Posted - 2007-07-27 : 11:28:55
Hi!

Look at this simple query.

SELECT a.ID,
(select SUM(b.amount) FROM tableB b WHERE b.paid = 0) AS totalDue
FROM tableA a

This will return the total sum of all records in tableB, for each result.

How do I make it return only the total due for each record. In other words, what't the correct syntax for this:

SELECT a.ID,
(select SUM(b.amount) FROM tableB b WHERE b.paid = 0 AND b.ID= #currentID#) AS totalDue
FROM tableA a

Thanks!

nr
SQLTeam MVY

12543 Posts

Posted - 2007-07-27 : 11:50:35
SELECT a.ID,
(select SUM(b.amount) FROM tableB b WHERE b.paid = 0 AND b.ID= a.ID) AS totalDue
FROM tableA a


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

chexone
Starting Member

6 Posts

Posted - 2007-07-27 : 12:00:28
Brilliant! Thank you!!
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-07-27 : 15:49:42
[code]SELECT a.ID,
SUM(ISNULL(b.Amount, 0)) AS TotalDue
FROM TableA AS a
LEFT JOIN TableB AS b ON b.ID = a.ID AND b.Paid = 0
GROUP BY a.ID[/code]

E 12°55'05.25"
N 56°04'39.16"

EDIT: nr found my sloppy work
Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2007-07-27 : 16:10:54
That would need a group by.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -