fhg
Volume 10, Number 4 -- January 27, 2010

Creating Yes/No Fields in SQL Queries

Published: January 27, 2010

Hey, Ted:

I want to retrieve a list of customers using SQL. I know how to select the customers I want. What I don't know how to do is create some columns that are not stored in the database, but must be built from information in other files. For example, I want a column that tells whether or not the customer has an open (unfulfilled) order. I'd also like a column that tells if he has ever bought a certain line of product. There are no fields in the customer master file that store this information. Can you help?

--Rick


Good question, Rick. You'll be glad to hear that this is not hard to do.

Let's assume you want all type-A customers (whatever that means).

select c.customerno, c.cusnam
  from customers as c
 where c.type = 'A'

Here they are:

CUSTOMERNO  CUSNAM
  12345     Cal E. Phornya
  23456     Billy Rubin
  34567     Polly Unsaturated
  45678     Molly Coddle

Let's assume that closed (or fulfilled) orders are indicated by a status code of "9" in the sales order header file. Here are the customers with open orders.

select distinct o.customerno, 'Yes' as HasActiveOrder
  from salesordh as o
 where o.status <> '9'

CUSTOMERNO  HASACTIVEORDER
  34567         Yes
  45678         Yes
  12345         Yes
  56789         Yes

Notice the use of DISTINCT to eliminate duplicate customer numbers from the list. Notice also that the literal "Yes" fills up a column named HasActiveOrder.

As for the customers who have ever ordered a certain line of product, let's assume the product line is in a class field in an item master file, and that the items a customer has ordered are in the sales order details file. Here are the customers who've ordered items from product line B3.

select distinct o.customerno, 'Yes' as BoughtB3
  from salesordh as o
  join salesordd as d
    on o.orderno = d.orderno
  join items as i
    on d.itemno = i.itemno
 where i.class='B3'

CUSTOMERNO  BOUGHTB3
  34567      Yes
  23456      Yes

This is the same sort of thing. DISTINCT removes duplicate customer numbers from the list, and the literal "Yes" indicates that the customer has bought product of class B3.

Now let's put it all together. We need to join the first query to the other two. We must use a left outer join, because some customers don't qualify for the last two queries. The HasActiveOrder and BoughtB3 columns will come back "null" for customers who are not returned by the last two queries, so we use the COALESCE function to convert nulls to the value No.

Here's the query:

select c.customerno, c.cusnam, 
       coalesce(act.HasActiveOrder,'No') as HasActiveOrder,
       coalesce(b3.BoughtB3,'No') as BoughtB3
  from customers as c
  left join 
          (select distinct o.customerno, 'Yes' as HasActiveOrder
                  from salesordh as o
                  where o.status <> '9') as act
    on c.customerno = act.customerno
  left join 
          (select distinct o.customerno, 'Yes' as BoughtB3
             from salesordh as o
             join salesordd as d
               on o.orderno = d.orderno
             join items as i
               on d.itemno = i.itemno
            where i.class='B3') as b3
    on c.customerno = b3.customerno
 where c.type = 'A'

And this is what the result might look like:

CUSTOMERNO CUSNAM             HASACTIVEORDER  BOUGHTB3
 12345     Cal E. Phornya     Yes             No
 23456     Billy Rubin        No              Yes
 34567     Polly Unsaturated  Yes             Yes
 45678     Molly Coddle       Yes             No

Isn't it great how we can put SQL SELECT statements in places once reserved for table and view names?

--Ted




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


Sponsored By
PRODATA COMPUTER SERVICES

Save the day with RDR and ProData utilities!

                                 RDR - retrieve deleted records. Then reactivate quickly & easily.

                                 DBU - database access made simple. The leading data access
                                 tool on the market.

                                 RDB - remote database access. Analyze data on all your servers.
                                 MySQL, Microsoft SQL Server, Oracle, DB2 databases and others.

                                 RDB Connect - programmatic access to remote data! Full SQL access to
                                 remote databases from all System i high-level languages.

Download your free trials NOW.
Order today and SAVE $$$!
www.prodatacomputer.com
800.228.6318


Senior Technical Editor: Ted Holt
Technical Editor: Joe Hertvik
Contributing Technical Editors: Erwin Earley, Brian Kelly, Michael Sansoterra
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

Help/Systems:  Event-driven job scheduling for UNIX, Linux, Windows & IBM i servers
LANSA:  Transport your apps to a new dimension with RAMP. FREE Webinar!
COMMON:  Join us at the annual 2010 conference, May 3 - 6, in Orlando, Florida


 

IT Jungle Store Top Book Picks

Easy Steps to Internet Programming for AS/400, iSeries, and System i: List Price, $49.95
The iSeries Express Web Implementer's Guide: List Price, $49.95
The System i RPG & RPG IV Tutorial and Lab Exercises: List Price, $59.95
The System i Pocket RPG & RPG IV Guide: List Price, $69.95
The iSeries Pocket Database Guide: List Price, $59.00
The iSeries Pocket SQL Guide: List Price, $59.00
The iSeries Pocket Query Guide: List Price, $49.00
The iSeries Pocket WebFacing Primer: List Price, $39.00
Migrating to WebSphere Express for iSeries: List Price, $49.00
Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00
Getting Started with WebSphere Express for iSeries: List Price, $49.00
Can the AS/400 Survive IBM?: List Price, $49.00
Chip Wars: List Price, $29.95


 
The Four Hundred
IBM Preps Power7 Launch For February

Looks Like i 7.1 Is Coming In April

The IBM Profit Engine Keeps A-Rolling in Q4

As I See It: What Did You Do At Work Today, Daddy?

The System iWant, 2010 Edition: Midrange Boxes

Four Hundred Stuff
Tripwire Rides Log Management Gig into SIEM Business

LANSA Likes Its Chances as Wal-Mart Ramps Up GDSN Mandate

CCSS Adds MIMIX Monitoring to i/OS Systems Management Suite

JobQGenie Now Protects Job Queue Contents Through IPLs

LTO 5 Speed, Capacity Lower Than Expected

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

System i PTF Guide
January 23, 2010: Volume 12, Number 04

January 16, 2010: Volume 12, Number 03

January 9, 2010: Volume 12, Number 02

January 2, 2010: Volume 12, Number 01

December 26, 2009: Volume 11, Number 52

December 19, 2009: Volume 11, Number 51

TPM at The Register
Voltaire pairs InfiniBand and Ethernet

Red Hat sponsors open source religion

VMware profits pinched in Q4

IT spending to rise in 2010, says Gartner

Platform and Calypso serve risk analysis to traders

Fujitsu puts systems chief at helm

Schwartz puts comforting arm around stricken Sun

Oracle: Mine is bigger and, um, more integrated

Liquid Computing evaporates staff

IBM buys spook-riddled DC services expert

IBM's Power7 servers imminent

China picks MIPS for super-duper super

THIS ISSUE SPONSORED BY:

ProData Computer Services
WorksRight Software
Halcyon Software


Printer Friendly Version


TABLE OF CONTENTS
Creating Yes/No Fields in SQL Queries

A Few Excel Export to CSV Tips

Admin Alert: Speeding Up i5/OS Access Path Rebuilds

Four Hundred Guru

BACK ISSUES




 
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-2010 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement