473,883 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL JOIN SYNTAX

MAB
Erland Sommarskog <so****@algonet .se> wrote in message
news:Xn******** **************@ 127.0.0.1...
MAB (fk************ *****@yahoo.com ) writes:
What I want is the sum of the amounts of the last payments of all
customers. Now the last payment of a customer is not necessarily the one
with the highest paymentid for that customer BUT it is the one with the
highest paymentid on the MOST RECENT date. We dont keep the time part
just the date so if there are more than 1 payments of a customer on a
date ( and there are many such cases ) only then the paymentid decides
which is the last payment. Further the last payment may be the last as
of today but I may want to find the sum of all the last payments upto
say March 1, 2003 or any date. My own solution is too slow even it is
correct.


This solution is not tested, as you did not provide any sample data:

SELECT SUM(p3.amount)
FROM Payments p3
JOIN (SELECT paymentid = MAX(p2.paymenti d)
FROM Payments p2
JOIN (SELECT p1.customerid, mostrecent = MAX(p1.date)
FROM Payments p1
WHERE p1.date <= '20030301'
GROUP BY p1.customerid) AS p1
ON p1.customerid = p2.customerid
AND p1.mostrecent = p2.date) AS p2
ON p3.paymentid = p2.paymentid

This solution is for SQL Server only. I don't know Access, so I can't
help with that.

As for performance, this is likely to be a case of finding the best
indexes. Clustered on (date, customerid) and nonclustered in (paymentid)
maybe.

Thanks. This looks fascinating. It looks correct too (although I havent
fully verified that). From this my next question
Is it possible to write your query in older join syntax like

FROM Payments p1, Payments p2
WHERE p1.customerid = p2.customerid etc.

Or is it that the newer syntax is superior such that you can do things with
it that you cant do with the older one?
I cant see how to write such a query the older way because you have only one
SELECT Clause there

Many thanks again

Jul 20 '05 #1
4 13516
Try:

SELECT SUM(p3.amount)
FROM Payments p3, (
SELECT paymentid = MAX(p2.paymenti d)
FROM Payments p2, (SELECT p1.customerid,
mostrecent = MAX(p1.date)
FROM Payments p1
WHERE p1.date <= '20030301'
GROUP BY p1.customerid) AS p1
WHERE p1.customerid = p2.customerid
AND p1.mostrecent = p2.date) AS p2
WHERE p3.paymentid = p2.paymentid ;

--
- Anith
( Please reply to newsgroups only )
Jul 20 '05 #2
MAB
SELECT SUM(p3.amount)
FROM Payments p3
JOIN (SELECT paymentid = MAX(p2.paymenti d)
FROM Payments p2
JOIN (SELECT p1.customerid, mostrecent = MAX(p1.date)
FROM Payments p1
WHERE p1.date <= '20030301'
GROUP BY p1.customerid) AS p1
ON p1.customerid = p2.customerid
AND p1.mostrecent = p2.date) AS p2
ON p3.paymentid = p2.paymentid

This solution is for SQL Server only. I don't know Access, so I can't
help with that.


Unfortunately this doesnt seem to work :(
It only brings the amount of 1 payment. So if you replace SUM(p3.amount)
with something like

p3.Paymentid, p3.customerid, p3.amount you only get 1 row which is obviously
incorrect because I need one paymentid ( the last one ) for each customer
and SUM(p3.amount) should get the total of all those records.
Can you fix this?

Jul 20 '05 #3
>> Can you fix this? <<

Not entirely, since I am not familiar with your requirements. All I have
done is simply changed the query with older syntax. If you need an exact &
accurate working solution, you'll have to provide the table DDLs (CREATE
TABLE statements ), sample data (INSERT statements) and expected results
along with a brief explanation of the required logic.

--
- Anith
( Please reply to newsgroups only )
Jul 20 '05 #4
MAB (fk************ *****@yahoo.com ) writes:
Unfortunately this doesnt seem to work :(
It only brings the amount of 1 payment. So if you replace SUM(p3.amount)
with something like

p3.Paymentid, p3.customerid, p3.amount you only get 1 row which is
obviously incorrect because I need one paymentid ( the last one ) for
each customer and SUM(p3.amount) should get the total of all those
records.
Can you fix this?


Maybe. As I pointed out in my original posting, the solution was
untested as you did not provide sample data and the expected result
from the sample.

So please post the following:

o CREATE TABLE statement for your table (which you already have, but
would be convenient with having all in one post.)
o INSERT statements with sample data.
o The expected result from the sample.

It would also be helpful if you repeated the problem as such, since you
did not post your reply as a followup to my post. By posting a followup,
it's easy for me to go back and review previous articles in the thread.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #5

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

Similar topics

3
5955
by: Phil Powell | last post by:
I'm not kidding, the only reason yesterday you didn't hear from me was because I wasn't coding, but today I am doing something quick, and yes, as always it failed.. right at the SQL statement: $sql = 'SELECT v.nnet_produkt_varegruppe_navn, ' . ' f.nnet_produkt_farge_navn, ' . ' s.nnet_produkt_storrelse_navn, ' . ' k.nnet_produkt_kvalitet_navn, ' . ' p.* ' .
2
2749
by: Pierre Fortin | last post by:
This quest for understanding started very innocently... A simple error on my part, passing on args as "args" instead of "*args" to os.path.join() led me to wonder why an error wasn't raised... def foo(*args): ... return os.path.join(*args) foo('a','b') # returns 'a/b'
2
18117
by: Martin | last post by:
I am now working on SQL Server 2000 having had previous experience on a different database. Both of the OUTER JOIN syntaxes is different from what I am used to and I am finding it slightly confusing. For example, given two tables : wipm_tbl_mi wipm_tbl_wi (which may not have data in it for a specific record that exists in the first table.)
3
44544
by: mheydman | last post by:
I apologize if this has been asked before- I searched google but could not find a concrete answer. I recently inherited a database whose t-sql code is written in a format that I find difficult to read (versus the format I have used for years). I have tested the queries below using the SQL Profiler, and both have identical costs. Is there any advantage of one format over the other?
8
4978
by: Matt | last post by:
Hello I have to tables ar and arb, ar holds articles and a swedish description, arb holds descriptions in other languages. I want to retreive all articles that match a criteria from ar and also display their corresponding entries in arb, but if there is NO entry in arb I still want it to show up as NULL or something, so that I can get the attention that there IS no language associated with that article.
2
1507
by: Good Man | last post by:
Hi there Yes, I've read about JOINs, albeit after coding for a couple of years already using queries like the following: "SELECT m.LastName, m.FirstName, o.Address FROM members m, offices o WHERE o.City='$vCity' AND m.Status<>'Retired' AND m.Status<>'Suspended' AND o.MemberID=m.MemberID ORDER BY LastName,FirstName" ($vCity comes from a drop-down list of city names)
3
23105
by: Ian Boyd | last post by:
i know nothing about DB2, but i'm sure this must be possible. i'm trying to get a client to create a view (which it turns out is called a "Logical" in DB2). The query needs a LEFT OUTER JOIN, but he doesn't know how to do that, or even if he can, and i don't have to time to learn DB2 from scratch right now. The following SQL Query is a trimmed sample of the full View (i.e. Logical) definition - and i would create it on an SQL based...
4
1944
by: Jean-Claude | last post by:
Hi, which is the faster query ? (of course, in my case the real queries are more complex) 1/ select * from file1 a join file2 b on b.key=a.key where b.data=123 and b.name='TEST'
52
6375
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible variations(combination of fields), - then act on each group in some way ...eg ProcessRs (oRs as RecordSet)... the following query will get me the distinct groups
7
5571
by: dunleav1 | last post by:
I have an application that uses the old join syntax instead of the SQL92 standards join syntax. I need to justify changing the code to the new standard. Is there any performance issue related to using the old syntax that are documented? Are there any other issues that I can use to justify a code upgrade?
0
9944
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
9797
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
10762
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...
1
10863
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,...
0
9586
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
7977
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
5807
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
6005
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3241
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.