fhg
Volume 7, Number 4 -- January 31, 2007

Finding the Last Transaction for a Customer

Published: January 31, 2007

Hey, Howard:

I've been studying your book, SQL at Work. I was hoping you would answer a question for me. We have a historical transaction file sorted on a descending date field. I'd like to only select the latest record for a specific ID with the most current date. I don't know the value of this date and I don't want it to return any other records. Is this possible? Thanks!

--Mary


This kind of query can be done using a subquery or a join operation. Let's create a sample table, load it with data, and try a few queries that demonstrate this technique. The following statement will create a transaction file that contains debit and credit transactions, customer identification number, and a quantity.

CREATE TABLE SQLBOOK.TRANSTEST
	(TRANSID INTEGER NOT NULL 
PRIMARY KEY 
GENERATED ALWAYS 
AS IDENTITY,
	 TRANSDATE DATE NOT NULL,
	 CUSTOMERID INTEGER NOT NULL,
	 TRANSTYPE CHAR(1) NOT NULL,
	 QUANTITY DECIMAL(10,2) NOT NULL);

Now execute the following statements to add data to the test table:

INSERT INTO SQLBOOK.TRANSTEST 
	(TRANSDATE,CUSTOMERID,TRANSTYPE,QUANTITY)
	VALUES ('01/01/1980',1,'C',100.33);
INSERT INTO SQLBOOK.TRANSTEST 
	(TRANSDATE,CUSTOMERID,TRANSTYPE,QUANTITY)
	VALUES ('02/02/1982',1,'D',10.21);
INSERT INTO SQLBOOK.TRANSTEST 
	(TRANSDATE,CUSTOMERID,TRANSTYPE,QUANTITY)
	VALUES ('03/03/1983',1,'C',1000.54);
INSERT INTO SQLBOOK.TRANSTEST 
	(TRANSDATE,CUSTOMERID,TRANSTYPE,QUANTITY)
	VALUES ('04/04/1984',1,'D',830.74);
INSERT INTO SQLBOOK.TRANSTEST 
	(TRANSDATE,CUSTOMERID,TRANSTYPE,QUANTITY)
	VALUES ('05/05/1985',1,'C',52.12);

Ok, now that we have data, let's think about a query strategy. In order to answer the query, you need two pieces of information, the customer number that you want to find the last transaction for and the date of the last transaction. To get the date of the last transaction for a customer, you can execute the following query:

SELECT MAX(TRANSDATE) 
FROM SQLBOOK.TRANSTEST
WHERE CUSTOMERID = 1;

Now, this query returns a single row with the date of the last transaction, to find that transaction record, we can join the result of this query to a query against the TRANSTEST file to find the rest of the field values in the target record. One syntax for accomplishing this is the following query:

SELECT * 
	FROM SQLBOOK.TRANSTEST AS A 
		INNER JOIN
			(SELECT MAX(TRANSDATE) AS MAXDATE 
				FROM SQLBOOK.TRANSTEST 
				WHERE CUSTOMERID = 1) AS B
		ON (MAXDATE = TRANSDATE)
	WHERE CUSTOMERID = 1 ;

Note that we open the TRANSTEST table and join it to the results of our max date query. This type of query can also be accomplished using a subquery. Here is an example:

SELECT * 
	FROM SQLBOOK.TRANSTEST AS A
	WHERE CUSTOMERID = 1 
	AND TRANSDATE = 
		(SELECT MAX(TRANSDATE) 
		FROM SQLBOOK.TRANSTEST AS B
		WHERE B.CUSTOMERID = A.CUSTOMERID);

Note that this is equivalent to what is being performed in the first example, in fact the iSeries will recognize that the subquery is actually a join operation and choose to implement the query as a join. Hope this helps!

--Howard


Howard Arner is vice president of Client Server Development. He spends his days writing software that talks to the System i5, iSeries, and AS/400 databases from Microsoft's .NET protocols. His book, SQL at Work is available at the IT Jungle online bookstore.


RELATED STORY

Retrieve a Representative of a Group



                     Post this story to del.icio.us
               Post this story to Digg
    Post this story to Slashdot


Sponsored By
PROFOUND LOGIC SOFTWARE

RPGsp - The Best of Both Worlds

The most comprehensive iSeries Web Development Environment for both building new Web apps and converting green-screens.

That's right! Use RPGsp to instantly convert any existing RPG/CL programs to a great-looking CGI application.

Or point RPGsp to your database files and instantly build new Inquiries, Drill-downs, File Maintenances, and other types of new Web applications.

The most comprehensive iSeries Web Development Environment for both building new Web apps and converting green-screens.

· WYSIWYG HTML Designer
· Integrated Visual Debugger
· Built-in Source Control
· Customizable Themes and Templates
· Easy to use Wizards
· Automated Server Configuration

Click here to download RPGsp.
Click to see videos of RPGsp in action!

Call 1-877-224-7768 or visit www.RPGsp.com


Senior Technical Editor: Ted Holt
Technical Editors: Howard Arner, Joe Hertvik, Shannon O'Donnell, Kevin Vandever
Contributing Technical Editors: Joel Cochran, Wayne O. Evans, Raymond Everhart,
Bruce Guetzkow, Brian Kelly, Marc Logemann, David Morris
Publisher and Advertising Director: Jenny Thomas
Advertising Sales Representative: Kim Reed
Contact the Editors: To contact anyone on the IT Jungle Team
Go to our contacts page and send us a message.

Sponsored Links

COMMON:  Join us at the 2007 conference, April 29 – May 3, in Anaheim, California
New Generation Software:  Leading provider of iSeries BI and financial management software
Twin Data:  System console control for AS/400s and LPARs from a LAN, WAN, VPN, or via Internet


Books on Sale at the IT Jungle Store: 30 Percent Off for 30 Days

The System i Pocket RPG & RPG IV Guide: List Price, $69.95; Sale Price, $49.00
The iSeries Pocket Database Guide: List Price, $59.00; Sale Price, $41.00
The iSeries Pocket Developers' Guide: List Price, $59.00; Sale Price, $41.00
The iSeries Pocket SQL Guide: List Price, $59.00; Sale Price, $41.00
The iSeries Pocket Query Guide: List Price, $49.00; Sale Price, $34.00
The iSeries Pocket WebFacing Primer: List Price, $39.00; Sale Price, $27.00
Migrating to WebSphere Express for iSeries: List Price, $49.00; Sale Price, $34.00
iSeries Express Web Implementer's Guide: List Price, $59.00; Sale Price, $41.00
Getting Started with WebSphere Development Studio for iSeries: List Price, $79.95; Sale Price, $56.00
Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00; Sale Price, $62.00
Getting Started with WebSphere Express for iSeries: List Price, $49.00; Sale Price, $34.00
WebFacing Application Design and Development Guide: List Price, $55.00; Sale Price, $38.00
Can the AS/400 Survive IBM?: List Price, $49.00; Sale Price, $34.00
The All-Everything Machine: List Price, $29.95; Sale Price, $21.00
Chip Wars: List Price, $29.95; Sale Price, $21.00

 

The Four Hundred
The Vanishing IT Woman--System i Women Respond

IBM Sells Printing Division to Ricoh for $725 Million

IT Salaries Rise by 5.2 in 2006, Dice Survey Says

As I See It: Measuring What Counts

The Linux Beacon
Novell Says SLED Is Better Than Windows Vista

AMD: Native Quad Core Opteron Will Best Intel Quasi Quads

IT Salaries Rise by 5.2 in 2006, Dice Survey Says

Ask TPM: The Economics of Open Source Software

Four Hundred Stuff
Idiom Translates Globalization Software into Strong Growth

PowerTech Looks to OpenService for Cross-Platform Security

Notes-Domino 8 Beta On Deck, Mid-Year GA Still on Schedule

mrc Hits the Throttle with Development Tools

Big Iron
IBM Buys Softek to Bolster Data Migration Offerings

Top Mainframe Stories From Around the Web

Chats, Webinars, Seminars, Shows, and Other Happenings

System i PTF Guide
January 27, 2007: Volume 9, Number 4

January 20, 2007: Volume 9, Number 3

January 13, 2007: Volume 9, Number 2

January 6, 2007: Volume 9, Number 1

December 30, 2006: Volume 8, Number 50

December 23, 2006: Volume 8, Number 49

The Windows Observer
Microsoft Keeps the Pressure on IBM's Notes, Domino

IBM Lotus Adds Handles to Information Overload

Symantec Expands Performance Management Software

Salesforce.com Reports AppExchange Milestone

The Unix Guardian
Sun Profits in Fiscal Q2, Gets $700 Million Equity Injection from KKR

Sun, Intel Form Alliance for Xeon Servers and Workstations

IBM Closes Out 2006 With a Strong Fourth Quarter

The X Factor: Solaris Versus Linux Support Pricing

Four Hundred Monitor
Four Hundred Monitor's
Full iSeries Events Calendar

THIS ISSUE SPONSORED BY:

Profound Logic Software
IBS
WorksRight Software



TABLE OF CONTENTS
Finding the Last Transaction for a Customer

Sorting Arrays and Subfiles with a User Index

When Fix Central Won't Let You Download PTFs

Four Hundred Guru

BACK ISSUES

From the IT Jungle Forums
Populate fields with file

Alert emails from iSeries

READC SUBFILE

CL Question on Overrides

Self referencing trigger





 
Subscription Information:
You can unsubscribe, change your email address, or sign up for any of IT Jungle's free e-newsletters through our Web site at http://www.itjungle.com/sub/subscribe.html.

Copyright © 1996-2008 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement