473,835 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about JOIN syntax

what is the syntax to join a table with the result of antoher query.

For example i have two tables

Create Table Customers (
CustomerID int,
LastPaymentDate Datetime )
Create Table Payments (
PaymentID int,
CustomerID int,
PaymentDate Datetime )

What query will bring me the customers whose lastpaymentdate in the
customers table is not correct.

That can only be checked by comparing it with the max paymentdate for each
customer in the payments table.

I want this to be done by ansi standard sql. Not using any specific feature
of sql server.

thx
Jul 20 '05 #1
11 3029
SELECT *
FROM Customers AS C
WHERE lastpaymentdate <>
(SELECT MAX(paymentdate )
FROM Payments AS P
WHERE P.customerid=C. customerid)

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #2

"David Portas" <RE************ *************** *@acm.org> wrote in message
news:2v******** ************@gi ganews.com...
SELECT *
FROM Customers AS C
WHERE lastpaymentdate <>
(SELECT MAX(paymentdate )
FROM Payments AS P
WHERE P.customerid=C. customerid)


oh may be my example was not the best!

what if I have

Create Table Customers (
CustomerID int,
LastPaymentAmou nt int,
LastPaymentDate Datetime )
Create Table Payments (
PaymentID int,
CustomerID int,
Amount int,
PaymentDate Datetime )

and I want to see if the LastPaymentAmou nt field holds correct values.
I couldnt use the max function for this obviously.

thx


Jul 20 '05 #3
> I couldnt use the max function for this obviously.

Why not? My query should still work.

If you want a query that uses a join then try this:

SELECT C.*
FROM Customers AS C
LEFT JOIN
(SELECT customerid, MAX(paymentdate ) AS lastpaymentdate
FROM Payments
GROUP BY customerid) AS P
ON C.customerid=P. customerid
AND C.lastpaymentda te=P.lastpaymen tdate
WHERE C.lastpaymentda te IS NOT NULL
AND P.customerid IS NULL

This has a possible advantage over the correlated subquery version. It will
include Customers who have a Lastpaymentdate but don't have any non-NULL
dates in the Payments table.

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #4
Oops, you wanted the *correct* values:

SELECT C.*
FROM Customers AS C
JOIN
(SELECT customerid, MAX(paymentdate ) AS lastpaymentdate
FROM Payments
GROUP BY customerid) AS P
ON C.customerid=P. customerid
AND C.lastpaymentda te=P.lastpaymen tdate

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #5

"David Portas" <RE************ *************** *@acm.org> wrote in message
news:4e******** ************@gi ganews.com...
Oops, you wanted the *correct* values:

SELECT C.*
FROM Customers AS C
JOIN
(SELECT customerid, MAX(paymentdate ) AS lastpaymentdate
FROM Payments
GROUP BY customerid) AS P
ON C.customerid=P. customerid
AND C.lastpaymentda te=P.lastpaymen tdate

--
David Portas
------------
Please reply only to the newsgroup
--


I want the LastPaymentAmou nt of Customers table to be compaired with the
Amount of the last payment in Payments table.
Ofcourse the last payment is the one with the maximum PaymentDate but the
Amount fields should be compared in both tables to see if they are equal.

Jul 20 '05 #6
You didn't include any keys or constraints with your DDL but I'll have to
assume that (customerid, paymentdate) is unique in Payments - otherwise how
will you define which payment is the latest?

SELECT C.customerid, C.lastpaymentam ount, C.lastpaymentda te
FROM
(SELECT customerid,
MAX(paymentdate ) AS paymentdate
FROM Payments
GROUP BY customerid) AS P1
JOIN Payments AS P2
ON P1.customerid = P2.customerid
AND P1.paymentdate = P2.paymentdate
JOIN Customers AS C
ON P2.customerid = C.customerid
AND P2.paymentdate = C.lastpaymentda te
AND P2.amount = C.lastpaymentam ount

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #7
>> what query will bring me the customers whose last_payment_da te in
the
customers table is not correct. <<

Your design is wrong; this is a computed value and you do not store
computed values in an RDBMS. Your Customers table should not exist at
all! And you do not have keys or anything that makes payments into a
table. Let's get the basics right:

CREATE TABLE Payments
(payment_id INTEGER NOT NULL PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES Customers
ON DELETE CASCADE
ON UPDATE CASCADE,
payment_date DATETIME DEFAULT CURRENT_TIMESTA MP NOT NULL);

Now create a VIEW which will always be correct:

CREATE VIEW CurrentPayments (payment_id, customer_id, payment_date)
AS
SELECT payment_id, customer_id, payment_date
FROM Payments AS P1
WHERE P1.payment_date
= (SELECT MAX(payment_dat e)
FROM Payments AS P2
WHERE P1.customer_id = P2.customer_id) ;
Jul 20 '05 #8
--CELKO-- (jo*******@nort hface.edu) writes:
Your design is wrong; this is a computed value and you do not store
computed values in an RDBMS.


Maybe in some small ideal model of a database you don't.

In real-world databases, you often find that you can save a lot of
cycles by storing computed data. For instance, if you have a transactions
table for a bank account, you probably want to store the balance on the
account after each transaction, because you will have several functions
in you system where you display this information. Having it computed
means that this function will run faster, and that the likelyhood that
they will show the wrong value because of bugs is less.

The one problem with storing computed values, is that if an underlying
value changes, the computed value changes too. But in the example I
just gave, this never happens due to business rules.
--
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 #9
>> In real-world databases, you often find that you can save a lot of
cycles by storing computed data. <<

OLAP versus versus OLTP databases. What I found is that the summary
data is usually processed by many applications at the same time (i.e.
end of the month, end of the quarter, end of the year), so you can
materialize the VIEWs and share them at that point in time instead of
always updating a redundant permanent table.

Unfortunately, SQL Server is not designed with that kind of sharing in
mind; it is more of a mainframe, heavy batch processing system approach.

--CELKO--
=============== ============
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #10

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

Similar topics

23
2569
by: phpfrizzle | last post by:
Hi there, I have a site with products on it. The site has a mysql backend. All products belong to certain series (table series). There can be up to 4 different products (table products) (categories 1-4) in 1 series. Each product has a defined 'series ID' which tells us
2
18115
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
44537
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
4977
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
1504
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
6477
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
4
11346
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
4
1942
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'
6
4035
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 use to justify a code upgrade?
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
9653
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
10815
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...
0
10526
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
10237
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
9348
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
7770
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
6970
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
5640
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...
3
3094
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.