23
Sat, Nov
1 New Articles

Practical SQL: Complex Filters Using Common Table Expressions

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

SQL allows you to do many things, but encapsulating logic isn't one of them…unless you understand the magic of Common Table Expressions (CTEs).

Recently, I've been doing a lot of data analysis. A lot of data analysis. I'm reviewing legacy data on a system that's been in production for over 20 years, and I’m trying to do forensic analysis on it. One of my projects is implementing some enhanced logic, but before it can be put into service, the stakeholders have to approve the changes, and the only way that happens is if I can provide detailed before and after numbers for the auditors. That means finding a way to apply ad hoc complex filters quickly and effectively in order to separate high- and low-impact effects.

They Be Stealin' My Bucket!

Sorry for the gratuitous use of an Internet meme; it happens to be one of my son's favorites. If you want to find it, just Google LOLRUS. But I digress; I just wanted a fun way to bring the word bucket into play, because that's the focus of this article. One of the most common filtering tasks I have to do during this analysis is to break up the data I'm summarizing into buckets by date. This wouldn't be too difficult except that the buckets are somewhat arbitrary, and they also change based on the subset of the data I'm looking at. Older data can be broken down by years, while newer data has to be down to months or even weeks. And the really tricky bit is that I don't know what the buckets need to be until I start breaking the data down into buckets.

And here's the best part: this is legacy data, which means the dates are stored as decimal values, not true dates. And we all know just how easy it is to perform date arithmetic with decimal numbers in SQL, right? Let's take a peek at the sort of calculation I have to do and see if you recognize the issue as one you've run into yourself. Let's say that, for the purposes of this example, I need to summarize production quantities into buckets. The calculations are a bit complex, including production quantities and values, but in order to keep the example manageable, I'll use only a single data point, the production quantity. So basically, I need to go through the file PRODHIST and summarize the quantity produced (PHQTY). Summarization needs to be by manufacturing site (PHSITE) as well as into buckets by date.

The date field is receipt date, PHRCDT, an eight-digit field. I'm going to give you the first, simplest breakdown: by one year, two years, and more than two years. We'll run off of July 1 of this year. Here's the first pass:

select PHSITE,

   sum(case when PHRCDT < 20150701

       then PHQTY else 0 end) YR2PLUS,

   sum(case when PHRCDT >= 20150701 and PHRCDT < 20160701

       then PHQTY else 0 end) YR2,

   sum(case when PHRCDT >= 20160701 and PHRCDT < 20170701

       then PHQTY else 0 end) YR1,

   sum(case when PHRCDT >= 20170701

       then PHQTY else 0 end) FUTURE

from PRODHIST group by PHSITE

What this will do is sum the PHQTY by PHSITE into four buckets.

Site       YR2PLUS            YR2            YR1          FUTURE

EAST   10,100,330.45   1,554,612.75   1,653,212.70     140,214.21

(...)

It's pretty simple. And it's relatively easy when you have hardcoded cutoffs. But what if you need to change the bucketing, perhaps to something a little more granular? As an example, let's look at the FUTURE bucket. We included it only on a whim because we know there can be no receipts later than today, but remember this is legacy data and you never know what you might find. So now the auditors would like all future data broken down by months, something like this:

select PHSITE, PHCLAS,

   sum(case when PHRCDT >= 20170701 and PHRCDT < 20170801

       then PHQTY else 0 end) MO1,

   sum(case when PHRCDT >= 20150801 and PHRCDT < 20160901

       then PHQTY else 0 end) MO2,

   sum(case when PHRCDT >= 20150901 and PHRCDT < 20161001

       then PHQTY else 0 end) MO3,

   sum(case when PHRCDT >= 20171001

       then PHQTY else 0 end) MO4PLUS

from PRODHIST group by PHSITE, PHCLAS

This wasn't terribly hard, because the number of columns was the same and again, I had hardcoded dates. All that were needed were a few modifications to the existing buckets and an extra comparison on the first one to skip older data. Once again, pretty simple. But now let's do a thought exercise. Say the auditors love this, but they want to run it regularly based on the current date. Ah, now we get interesting.

Date Arithmetic in SQL

This shouldn't be too hard, right? Basically, I just want something like this:

sum(case when PHRCDT >= CURRENT_DATE

         and PHRCDT < CURRENT_DATE + 1 MONTH

   then PHQTY else 0 end) MO1,

I have to repeat this for each bucket, but I think that would be acceptable if it weren't for the pesky fact that PHRCDT isn't a date field. It's a legacy standard eight-digit decimal field, and that's not going to work very well. Now, I could update the statement to dynamically convert one of the operands or the other so that they are compatible. Back in the olden days that might be something like this:

sum (case

when date(substr(digits(PHRCDT),1,4) || '-' ||    

           substr(digits(PHRCDT),5,2) || '-' ||    

           substr(digits(PHRCDT),7,2)) >= CURRENT_DATE

   and date(substr(digits(PHRCDT),1,4) || '-' ||    

           substr(digits(PHRCDT),5,2) || '-' ||    

           substr(digits(PHRCDT),7,2)) < CURRENT_DATE + 1 MONTH

then PHQTY else 0 end) MO1,

Just imagine that repeated for every bucket. Suddenly a simple bucketing explodes into dozens of lines of code that are easy to break with a simple transposition. I've actually seen code like this, and I'll wager you have, too. The other option is to convert the date to CCYYMMDD, something I talked about in a previous article on date formatting. It works, but it isn't much cleaner:

sum(case

when PHRCDT >=

   decimal(to_char(CURRENT_TIMESTAMP, 'YYYYMMDD'),8,0))

and PHRCDT <

   decimal(to_char(CURRENT_TIMESTAMP + 1 MONTH, 'YYYYMMDD'),8,0))

then PHQTY else 0 end) MO1,

There are other way to convert dates to decimal, but they're no easier to understand, and I still need to repeat whatever I do for every bucket. Twice, in fact. And if the auditors need me to summarize another field (say, the count of receipts), I then have to duplicate that whole mess again. The readability is way down, the chance for a typo way up, and all in all this is just going in a bad direction.

Common Table Expressions to the Rescue!

And now to the solution, our good friend the Common Table Expression, or CTE! With the CTE, I can do all the bucketing calculations up front and then use those results for my buckets, no matter how many I need. I can easily change the bucketing in one place.

First, let's look at the modified code.

-- Define bucket cutoff dates

with t1(LOWEST, B1CUT, B2CUT, B3CUT) as (values (              

   decimal(to_char(CURRENT_TIMESTAMP,'YYYYMMDD'),8,0),

   decimal(to_char(CURRENT_TIMESTAMP + 1 MONTHS,'YYYYMMDD'),8,0),

   decimal(to_char(CURRENT_TIMESTAMP + 2 MONTHS,'YYYYMMDD'),8,0),

   decimal(to_char(CURRENT_TIMESTAMP + 3 MONTHS,'YYYYMMDD'),8,0)))          

-- Summarize production into buckets

select PHSITE, PHCLAS,

   sum(case when PHRCDT >= LOWEST and PHRCDT < B1CUT

       then PHQTY else 0 end) BUCKET1,

   sum(case when PHRCDT >= B1CUT and PHRCDT < B2CUT

       then PHQTY else 0 end) YR2,

   sum(case when PHRCDT >= B2CUT and PHRCDT < B3CUT

       then PHQTY else 0 end) YR1,

   sum(case when PHRCDT >= B3CUT

       then PHQTY else 0 end) BUCKET4

from PRODHIST cross join T1 group by PHSITE, PHCLAS

The definition of the CTE T1 allows us to create as many buckets as we need and assign names to all of them. In this case, the lowest summarized date is today's date, and subsequent cutoffs are today plus one month, plus two months, and plus three months. That particular code is in its own section.

In the next, separate section of the SQL statement, I use those values to summarize my data. I've changed the names of the resulting sums to be the more generic BUCKET1–BUCKET4, which would make it pretty easy to extend the code. Also, you might notice the use of the rather rare CROSS JOIN clause. It's rare because it means to join every record in the first table with every record in the second table, which isn't something you normally do. But it makes perfect sense here, because the T1 CTE has only one record, and I want to use that record to act on every record in the PRODHIST file.

So now, whenever the auditors want a slightly different bucketing of the results, I just change the definition of T1. If I'm particularly lazy (I mean efficient!), I just change the second half to some arbitrarily large number of buckets, say 10. If the auditors ask for 5 buckets, I just repeat the last cutoff for buckets 6–10 and don't include those columns in the report I hand back to them. Done!

So, I hope you get a feel for how you can use CTEs to encapsulate complex logic in your SQL statements. This will reduce duplication and make your code less error-prone and more future-proof. Have fun with CTEs!

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: