473,761 Members | 10,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_OPENDAT E is in the same
month as the PORTFOLIO_OPEND ATE, then sum the account_openamt for the
same PRODUCT, and update the CHECKING_OPENAM T, SAVINGS_OPENAMT ,
CD_OPENAMT, etc in table PORTFOLIO. For other accounts opened NOT in
the same month as the PORTFOLIO_OPEND ATE, just ignore them.

--Here are the tables
create table portfolio
(portfolio_id int
,portfolio_open date smalldatetime
,checking_opena mt money
,savings_openam t 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_openda te smalldatetime
,account_openam t money)

insert into account values(1,'check ing','2/15/2005',2000)
insert into account values(1,'check ing','2/20/2005',3000)
insert into account values(1,'savin gs','2/20/2005',3000)
insert into account values(1,'cd',' 5/15/2005',5000)

--Ideal Output--
id portfolio_opend ate checking_openam t savings_openamt cd_openamt
1 2/15/2005 5000 3000 0

--Here is my query:
update portfolio
set checking_openam t=sum(b.account _openamt) --problem appears!
from portfolio as a
join account as b
on a.id=b.id
and year(a.portfoli o_opendate)=yea r(b.account_ope ndate)
and month(a.portfol io_opendate)=mo nth(b.account_o pendate)
and product ='checking'
--and product='saving s'
--and product='cd'

Thanks again!!

Feb 15 '06 #1
3 1584
Hi, rola

Your portfolio table SHOULD NOT contain the checking_openam t,
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_ope ndate,
s.checking_open amt, s.savings_opena mt, s.cd_openamt
FROM portfolio p LEFT JOIN (
SELECT portfolio_id,
MONTH(account_o pendate) as account_month,
YEAR(account_op endate) as account_year,
SUM(CASE WHEN product='checki ng' THEN account_openamt ELSE 0 END)
as checking_openam t,
SUM(CASE WHEN product='saving s' 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_o pendate),
YEAR(account_op endate)
) s ON p.portfolio_id= s.portfolio_id
AND MONTH(portfolio _opendate)=acco unt_month
AND YEAR(portfolio_ opendate)=accou nt_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_openam t = a.checkamt,
savings_openamt = a.saveamt,
cd_openamt = a.cdamt
FROM portfolio p
JOIN (SELECT portfolio_id,
month = convert(char(6) , account_opendat e, 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_opendat e, 112)
) AS a ON p.portfolio_id = a.portfolio_id
AND convert(char(6) , p.portfolio_ope ndate, 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****@sommarsk og.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
3435
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 new values are updated in all corresponding tables (the function of the pages in question). However, on the page that does the DB update, I also want to do some checks on the data before performing the update. Now, the problem that I am...
3
4685
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 your help. update XSORA1A.XS0011T_STATISTIQUES_UNIX a
4
11261
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 the content in a table changed, is it necessary for a old recordset to renew itself by do "Requery()"? Thanks for your help!
8
89315
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 tblMyTable.UniqueID = tblMyTableTEMP.UniqueID SET tblMyTable.myField = tblMyTableTEMP.myField, tblMyTable.myField2 = tblMyTableTEMP.myField2,
2
8541
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 example of what I'm trying to do is below: update (tbl_ind_mananas LEFT JOIN (select count(*) as count, (dubicacion || zona || manzana) as cod_manzana from tbl_censo_poblacion_1993 group by dubicacion, zona, manzana) tbl1 on relacion = cod_manzana) as...
3
53772
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 a specific need to only add a new field to a table if possible. Here's a simplified example of what I'm trying to do: I get a file with the following two fields: First Name
4
11340
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 AddressDescription of Entity 456 = AddressDescription of Entity_ID 123 Address1 of Entity 456 = Address1 of Entity_ID 123 City of Entity 456 = City of Entity_ID 123
2
5070
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 underlying subquery to this Update query involves a MAX function on a date field, which is then used in the DLookup statement. Any help appreciated. Thanks Richard
9
3062
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. Below you will find the code I've written and the error that results. I'm hoping that someone can give me some direction as to what syntax or parameter is missing from the code that is expected by VBA. Overview: I'm trying to copy calculated...
16
3517
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 renaming the duplicate records? My thinking was to take the results of the duplicate query, and somehow have it number each line where there is a duplicate (tried a groups query, but "count" won't work), then do an update query to change the duplicate to...
0
9531
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9905
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6609
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3881
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.