SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How do i rewrite this query?
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

PGG_CA
Starting Member

16 Posts

Posted - 06/14/2012 :  11:39:39  Show Profile  Reply with Quote
I have these tables and fields:

TableA
fields: id, totaltime

TableB
fields: id, time_min

Sample Data:

TableA
100, NULL
101, NULL
102, NULL

TableB
100, 5
100, 10
101, 12
101, 4
101, 6
102, 2

I have this query that would update the totaltime field in TableA with a sum of the time_min for each ID. TableA, after the update query, should now look like this:

TableA
100, 15
101, 22
102, 2


UPDATE a
SET a.totaltime = (SELECT SUM(TableB.time_min) FROM TableB inner join
TableA on TableB.id = TableA.id GROUP BY TableA.id)
FROM TableA a inner join TableB b on a.id=b.id

When I execute it, I get the error: Subquery returned more than 1 value. This not permitted when the subquery follows =, ... or when the subquery i used as an expression.

How do I accomplish what I want to do?

nigelrivett
Flowing Fount of Yak Knowledge

United Kingdom
3328 Posts

Posted - 06/14/2012 :  12:00:49  Show Profile  Visit nigelrivett's Homepage  Reply with Quote
update tableA
set totaltime = (select sum(time_min) from TableB b where a.id = b.id)
from TableA a

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

Transact Charlie
Flowing Fount of Yak Knowledge

United Kingdom
3442 Posts

Posted - 06/14/2012 :  12:01:20  Show Profile  Visit Transact Charlie's Homepage  Reply with Quote
malformed. There are many different ways.

Here using a derived table

UPDATE a SET
	[totalTime] = sumb.[total]
FROM
	TableA AS a
	JOIN (
		SELECT
			b.[id] AS [id]
			, SUM(b.[Time_min]) AS [total]
		FROM
			TableB AS b
		GROUP BY
			b.[id]
		)
		AS sumb ON sumb.[id] = a.[ID]


Transact Charlie

Msg 3903.. The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000