473,394 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Query Help with Update statement, thanks!

Hi Group!

I am having a problem of using SUM under UPDATE statement. I understand
that SQL does not allow me to use SUM in UPDATE, but unfortunately, I
can not find a way to get around it. Can someone please give me some
idea? Thanks a million!

--Here is the criteria:
Under the same PORTFOLIO_ID, if the ACCOUNT_OPENDATE is in the same
month as the PORTFOLIO_OPENDATE, then sum the account_openamt for the
same PRODUCT, and update the CHECKING_OPENAMT, SAVINGS_OPENAMT,
CD_OPENAMT, etc in table PORTFOLIO. For other accounts opened NOT in
the same month as the PORTFOLIO_OPENDATE, just ignore them.

--Here are the tables
create table portfolio
(portfolio_id int
,portfolio_opendate smalldatetime
,checking_openamt money
,savings_openamt money
,cd_openamt money)

insert into portfolio values(1,'2/15/2005',0,0,0)

create table account
(portfolio_id int
,product varchar(20)
,account_opendate smalldatetime
,account_openamt money)

insert into account values(1,'checking','2/15/2005',2000)
insert into account values(1,'checking','2/20/2005',3000)
insert into account values(1,'savings','2/20/2005',3000)
insert into account values(1,'cd','5/15/2005',5000)

--Ideal Output--
id portfolio_opendate checking_openamt savings_openamt cd_openamt
1 2/15/2005 5000 3000 0

--Here is my query:
update portfolio
set checking_openamt=sum(b.account_openamt) --problem appears!
from portfolio as a
join account as b
on a.id=b.id
and year(a.portfolio_opendate)=year(b.account_opendate )
and month(a.portfolio_opendate)=month(b.account_openda te)
and product ='checking'
--and product='savings'
--and product='cd'

Thanks again!!

Feb 15 '06 #1
3 1568
Hi, rola

Your portfolio table SHOULD NOT contain the checking_openamt,
savings_openamt and cd_openamt columns. These columns should be
computed using a view, like this:

CREATE VIEW portfolio_view AS
SELECT p.portfolio_id, p.portfolio_opendate,
s.checking_openamt, s.savings_openamt, s.cd_openamt
FROM portfolio p LEFT JOIN (
SELECT portfolio_id,
MONTH(account_opendate) as account_month,
YEAR(account_opendate) as account_year,
SUM(CASE WHEN product='checking' THEN account_openamt ELSE 0 END)
as checking_openamt,
SUM(CASE WHEN product='savings' THEN account_openamt ELSE 0 END)
as savings_openamt,
SUM(CASE WHEN product='cd' THEN account_openamt ELSE 0 END)
as cd_openamt
FROM account
GROUP BY portfolio_id, MONTH(account_opendate),
YEAR(account_opendate)
) s ON p.portfolio_id=s.portfolio_id
AND MONTH(portfolio_opendate)=account_month
AND YEAR(portfolio_opendate)=account_year

It is possible to use an UPDATE statement with SUM() in a subquery to
fill these values in the portfolio table, but this should not be done
because it creates redundancy and this leads to possible
inconsistencies. To ensure that you don't have inconsistencies, you can
write the UPDATE-s in a trigger, but you also need to ensure that the
destination columns won't be updated directly. In conclusion, it's best
to do this using a view.

Razvan

Feb 15 '06 #2
Thank you so much Razvan! That's a great help!!

Feb 15 '06 #3
rola (ro******@gmail.com) writes:
I am having a problem of using SUM under UPDATE statement. I understand
that SQL does not allow me to use SUM in UPDATE, but unfortunately, I
can not find a way to get around it. Can someone please give me some
idea? Thanks a million!


That's easily done with a derived table:

UPDATE portfolio
SET checking_openamt = a.checkamt,
savings_openamt = a.saveamt,
cd_openamt = a.cdamt
FROM portfolio p
JOIN (SELECT portfolio_id,
month = convert(char(6), account_opendate, 112),
checkamt = SUM(CASE product
WHEN 'checking' THEN account_openamt
ELSE 0
END),
saveamt = SUM(CASE product
WHEN 'savings' THEN account_openamt
ELSE 0
END),
cdamt = SUM(CASE product
WHEN 'cd' THEN account_openamt
ELSE 0
END)
FROM account
GROUP BY portfolio_id, convert(char(6), account_opendate, 112)
) AS a ON p.portfolio_id = a.portfolio_id
AND convert(char(6), p.portfolio_opendate, 112) = a.month

A derived table is a virtual temp table within the query. The
compuation order may be different, this is just a logical way of
express it. This is a very powerful tool to handle complex queries.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Feb 15 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: jaysonsch | last post by:
Hello! I am having some problems with a database query that I am trying to do. I am trying to develop a way to search a database for an entry and then edit the existing values. Upon submit, the...
3
by: Nicolas Payre | last post by:
Hi, I have the following SQL that I want to use to update a table. It doesn't work ! Does someone knows why? ** I Know it could be done easy with a CURSOR FOR LOOP, but still... Thanks for...
4
by: sci | last post by:
Could someone help me by answering the questions below? What's a cursor? What's difference between Query and View? Is a RecordSet just part of a table? Can it be part of a query of view? If...
8
by: Lauren Quantrell | last post by:
In VBA, I constructed the following to update all records in tblmyTable with each records in tblmyTableTEMP having the same UniqueID: UPDATE tblMyTable RIGHT JOIN tblMyTableTEMP ON...
2
by: Mike Leahy | last post by:
Hello all, This question is related to updating tables - is there any way to calculate or update the values in a column in a table to the values in a field produced by a query result? An...
3
by: GL | last post by:
Hi, Is there a way to add a field to an existing table using a query of some sort (without needing to manually add a field to the table). I know how to do it with a make table query, but I have...
4
by: deko | last post by:
I'm trying to update the address record of an existing record in my mdb with values from another existing record in the same table. In pseudo code it might look like this: UPDATE tblAddress SET...
2
by: bobabooey2k | last post by:
I have an update query with one field having in its "Update to" cell a DLookup statement. This query takes 2-3 minutes on 3000 records. Can I avoid dlookup here using multiple queries? An...
9
by: Kelii | last post by:
I've been trying to get this piece to work for a few hours, but have given up. I hope someone out there can help, I think the issue is relatively straightforward, but being a novice, I'm stumped....
16
by: ARC | last post by:
Hello all, So I'm knee deep in this import utility program, and am coming up with all sorts of "gotcha's!". 1st off. On a "Find Duplicates Query", does anyone have a good solution for...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.