473,756 Members | 4,256 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with complex single-table UPDATE query


I am trying to write an SQL UPDATE statement for an MSAccess table and
am having some problems getting my head around it. Can anyone help?

TableName: CustTransaction s
TransactionKey AutoNumber (Primary Key)
CustomerID Long Integer (Non-unique index)
AmountSpent Double
CustSelected Boolean

What I would like to do is, for all of the records in descending order
of "AmountSpen t" where "CustSelect ed = TRUE", set CustSelected to FALSE
such that the sum of all the AmountSpent records is no greater than a
specified amount (say $50,000).

What I'm doing at the moment is a "SELECT * FROM CustTransaction s WHERE
CustSelected = TRUE ORDER BY AmountSpent;", programatically looping
through all the records until AmountSpent 50000, then continuine to
loop through the remainder of the records setting CustSelected = FALSE.
This works but is slow and inefficient. I just know it could be done in
a single SQL statement with subqueries, but I can't figure it out.

The closest I can get is:-

UPDATE CustTransaction s SET CustSelected = FALSE
WHERE (CustSelected = TRUE)
AND TransactionKey NOT IN
(SELECT TOP 50000 TransactionKey FROM CustTransaction s WHERE
(((CustTransact ions.CustSelect ed)=TRUE))
ORDER BY AmountSpect DESC, TransactionKey ASC);

However, this mereley ensures only the top 50,000 customers by amount
spent are "selected", not the top "X" customers who have spent a total
of $50,000. I really need to replace the "SELECT TOP 50000" with some
form of "SELECT TOP (X rows until sum(AmountSpent ) =50000)".

Is it even possible to achieve what I'm trying to do?

Thanks in advance for any assistance offered!
--
SlowerThanYou
Nov 17 '06 #1
3 2448
I think your subquery should look something like:

SELECT TOP X CustomerID FROM CustTransaction s WHERE (DSum("[AmountSpent]","
[CustTransaction s]","[CustomerID]=" & [CustomerID]) 50000);

However, since this uses an aggregate function, Access might not let you
update any records. You could use this query to create a temporary table and
then join on [CustomerID] in a regular update query. HTH

Slower Than You wrote:
>I am trying to write an SQL UPDATE statement for an MSAccess table and
am having some problems getting my head around it. Can anyone help?

TableName: CustTransaction s
TransactionK ey AutoNumber (Primary Key)
CustomerID Long Integer (Non-unique index)
AmountSpent Double
CustSelected Boolean

What I would like to do is, for all of the records in descending order
of "AmountSpen t" where "CustSelect ed = TRUE", set CustSelected to FALSE
such that the sum of all the AmountSpent records is no greater than a
specified amount (say $50,000).

What I'm doing at the moment is a "SELECT * FROM CustTransaction s WHERE
CustSelected = TRUE ORDER BY AmountSpent;", programatically looping
through all the records until AmountSpent 50000, then continuine to
loop through the remainder of the records setting CustSelected = FALSE.
This works but is slow and inefficient. I just know it could be done in
a single SQL statement with subqueries, but I can't figure it out.

The closest I can get is:-

UPDATE CustTransaction s SET CustSelected = FALSE
WHERE (CustSelected = TRUE)
AND TransactionKey NOT IN
(SELECT TOP 50000 TransactionKey FROM CustTransaction s WHERE
(((CustTransact ions.CustSelect ed)=TRUE))
ORDER BY AmountSpect DESC, TransactionKey ASC);

However, this mereley ensures only the top 50,000 customers by amount
spent are "selected", not the top "X" customers who have spent a total
of $50,000. I really need to replace the "SELECT TOP 50000" with some
form of "SELECT TOP (X rows until sum(AmountSpent ) =50000)".

Is it even possible to achieve what I'm trying to do?

Thanks in advance for any assistance offered!
--
Message posted via http://www.accessmonster.com

Nov 17 '06 #2

Slower Than You wrote:
I am trying to write an SQL UPDATE statement for an MSAccess table and
am having some problems getting my head around it. Can anyone help?

TableName: CustTransaction s
TransactionKey AutoNumber (Primary Key)
CustomerID Long Integer (Non-unique index)
AmountSpent Double
CustSelected Boolean

What I would like to do is, for all of the records in descending order
of "AmountSpen t" where "CustSelect ed = TRUE", set CustSelected to FALSE
such that the sum of all the AmountSpent records is no greater than a
specified amount (say $50,000).

What I'm doing at the moment is a "SELECT * FROM CustTransaction s WHERE
CustSelected = TRUE ORDER BY AmountSpent;", programatically looping
through all the records until AmountSpent 50000, then continuine to
loop through the remainder of the records setting CustSelected = FALSE.
This works but is slow and inefficient. I just know it could be done in
a single SQL statement with subqueries, but I can't figure it out.

The closest I can get is:-

UPDATE CustTransaction s SET CustSelected = FALSE
WHERE (CustSelected = TRUE)
AND TransactionKey NOT IN
(SELECT TOP 50000 TransactionKey FROM CustTransaction s WHERE
(((CustTransact ions.CustSelect ed)=TRUE))
ORDER BY AmountSpect DESC, TransactionKey ASC);

However, this mereley ensures only the top 50,000 customers by amount
spent are "selected", not the top "X" customers who have spent a total
of $50,000. I really need to replace the "SELECT TOP 50000" with some
form of "SELECT TOP (X rows until sum(AmountSpent ) =50000)".

Is it even possible to achieve what I'm trying to do?
you can't use a parameter to specify the number of top values to return
in a SQL query. (I know, because I asked this question several years
ago...) You could create a form to get the number of values you want
returned and then modify the querydef's SQL statement.

What it sounds like you're trying to do is something like a
check-processing scenario, where you have something like an account
balance and then a list of checks to clear against the account, and you
want to clear all the checks you can up to the point you hit the
"insufficie nt funds" problem. Unless I'm completely clueless, you'd
have to open an updatable recordset of outstanding checks and then
process

dim rs as DAO.Recordset
set rs=...
do until rs.EOF Or curBalance < rs.Fields("Chec kAmount")
'--decrease amount of available funds
curBalance=curb alance - rs.fields("Chec kAmount")
'---set the clear date/flags
rs.Edit
rs.Fields("Clea rDate")=Now
rs.Update
rs.MoveNext
loop

Nov 17 '06 #3
In article <11************ ****@proxy00.ne ws.clara.net>,
no.way@jose says...
>
I am trying to write an SQL UPDATE statement for an MSAccess table and
am having some problems getting my head around it. Can anyone help?

TableName: CustTransaction s
TransactionKey AutoNumber (Primary Key)
CustomerID Long Integer (Non-unique index)
AmountSpent Double
CustSelected Boolean

What I would like to do is, for all of the records in descending order
of "AmountSpen t" where "CustSelect ed = TRUE", set CustSelected to FALSE
such that the sum of all the AmountSpent records is no greater than a
specified amount (say $50,000).

What I'm doing at the moment is a "SELECT * FROM CustTransaction s WHERE
CustSelected = TRUE ORDER BY AmountSpent;", programatically looping
through all the records until AmountSpent 50000, then continuine to
loop through the remainder of the records setting CustSelected = FALSE.
This works but is slow and inefficient. I just know it could be done in
a single SQL statement with subqueries, but I can't figure it out.

The closest I can get is:-

UPDATE CustTransaction s SET CustSelected = FALSE
WHERE (CustSelected = TRUE)
AND TransactionKey NOT IN
(SELECT TOP 50000 TransactionKey FROM CustTransaction s WHERE
(((CustTransact ions.CustSelect ed)=TRUE))
ORDER BY AmountSpect DESC, TransactionKey ASC);

However, this mereley ensures only the top 50,000 customers by amount
spent are "selected", not the top "X" customers who have spent a total
of $50,000. I really need to replace the "SELECT TOP 50000" with some
form of "SELECT TOP (X rows until sum(AmountSpent ) =50000)".

Is it even possible to achieve what I'm trying to do?

Thanks in advance for any assistance offered!

really need to replace the "SELECT TOP 50000" with some
form of "SELECT TOP (X rows until sum(AmountSpent ) =50000)".
It seems that this is asking for both a ranking and a running
sum and
may require two queries.

SELECT CustTransaction s.TransactionKe y,
CustTransaction s.CustomerID,
CustTransaction s.AmountSpent,
CustTransaction s.CustSelected,
(SELECT COUNT(* )
FROM CustTransaction s AS ct2
WHERE CustTransaction s.AmountSpent < ct2.AmountSpent
OR (CustTransactio ns.AmountSpent = ct2.AmountSpent
AND CustTransaction s.TransactionKe y <=
ct2.Transaction Key)) AS Rank
FROM CustTransaction s
WHERE CustTransaction s.CustSelected = True;

UPDATE CustTransaction s SET CustSelected = FALSE
WHERE TransactionKey = ANY (SELECT a.TransactionKe y
FROM Ranked_Customer _Transactions AS a
INNER JOIN Ranked_Customer _Transactions AS b
ON b.Rank <= a.Rank
GROUP BY a.TransactionKe y
HAVING SUM(b.AmountSpe nt) <= [Enter dollar amount:]);
Nov 18 '06 #4

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

Similar topics

0
3473
by: abcd | last post by:
kutthaense Secretary Djetvedehald H. Rumsfeld legai predicted eventual vicmadhlary in Iraq mariyu Afghmadhlaistmadhla, kaani jetvedehly after "a ljetvedehg, hard slog," mariyu vede legai pressed Pentagjetvedeh karuvificials madhla reachathe strategy in karkun campaign deshatinst terrorism. "mudivae maretu winning or losing karkun global varti jetvedeh terror?" Mr. Rumsfeld adugued in a recent memormariyuum. vede velli jetvedeh madhla...
21
4137
by: Blair | last post by:
could someone PLEASE tell me why this doesn't work... ----------------------------------------- #include <complex> using namespace std; typedef complex<long double> cld; void main() { cld cmplx, temp;
16
2590
by: expertware | last post by:
Dear friends, My name is Pamela, I do not know anything about javascript, but I would like to ask if it offers a solution to this problem of mine. I have an image on a web page within a css layer: <DIV ID=MyLayer STYLE = "position: absolute;top:68px; left:563px;
27
2112
by: SK | last post by:
Hi I am trying to teach myself how to program in C. I am a physician hoping to be able to help restructure my office. Anyhow, I amhoping that the porblem I am having is simple to those much more experienced in programming. I am trying to use the concept of arrays to calculate the hours of my backoffice staff, however I am getting a ridiculous amount of error lines. If any one has time to help me that would be great. I am using the...
4
1789
by: Miguel Dias Moura | last post by:
Hello, i created an ASP.net / VB page with a really big form. Now i want to create 4 pages and in each one i will place 1/4 of the big form. The last page will send all the form values by email. How can i send the form values from one page to the next one?
3
1938
by: Sky Sigal | last post by:
I coming unglued... really need some help. 3 days chasing my tail all over MSDN's documentation ...and I'm getting nowhere. I have a problem with TypeConverters and storage of expandableobjects to attributes in tags (think Style tag -> Style object). The problem that I am chasing is: Html side:
18
2163
by: Peteroid | last post by:
Apparently there is a limit to how complex a single header file with a huge class definition in it can be. The source to one of my header files is at a point that it compiles and runs fine, until I add one more line to it, and I then get this compiler error: fatal error C1026: parser stack overflow, program too complex This diagnostic occurred in the compiler generated function 'void My_Class::Dispose(bool)' Has this happened to...
23
3205
by: keyser_Soze | last post by:
I have MS Visual Studio 2003 on Windows XP Pro. I have IIS running on this machine and I am trying to debug some existing code which has both ASP and ASP.NET components. When I try and launch the debugger from VS, I am told it can't because the project is of output type class library. The error indicates I should set the start action to start external program or start URL. I tried both of these and cannot seem to get the debugger to...
1
1552
by: MikeZdoesit | last post by:
Hi, I'm having trouble with setting up a shared object and I really need some help from someone more enlighten then myself in the field of actionscript :) Basically I have a talking character that introduces a site and says hello (basically an intro) but I don’t want him to repeat his speech every single time the area gets refreshed or the page gets revisited. On top of that I don’t want the speech to get skipped once and never seen again, I...
4
1600
by: MyRedz | last post by:
hi mate.. i want to change my struct text in typedef struct{double r; double i;} COMPLEX; assume i want to change it to normal one without the typedef thing and do it like this struct COMPLEX {double r; double i;};]
0
9462
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
9886
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9722
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8723
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7259
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
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
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
2
3369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.