02
Sat, Nov
2 New Articles

The Hidden Power of Query, Part 2

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

This is the second in a series of articles on using IBM Query for AS/400 (a.k.a. Query/400 or Query) to its maximum potential. In “The Hidden Power of Query, Part 1” (the October 2000 issue of MC), I demonstrated how to utilize the available functions in Query to get the most out of the reporting tool, using a single data file as input. When these techniques are combined with multiple input and output files, the report writer takes on another dimension.

Input from Multiple Files

One of the more powerful attributes of Query is its ability to let you choose not only which files to include in your report, but also how they will be linked. Extract information from more than one file by using F9 in Specify File Selections after you’ve identified your first (or Primary) data file. Each subsequent F9 will add a link to another file.

Query can join files together in three ways—Matched, Matched with Primary, and Unmatched.

• Matched Records will show records that are in both file 1 and file 2. If there is no corresponding record in file 2, the Query report will not include information from file 1 either.

• Matched with Primary will show all records in file 1 and any corresponding records that it can find in file 2. If there is no corresponding record in file 2, the Query report will return default values (usually blanks or zeros) in the file 2 fields, depending on their data types.

• Unmatched with Primary will show all records in file 1 that are not in file 2.

With any file join option, you will need to tell the report which fields from files 1 and 2 that you’d like to use as a common thread. Query will try to match each single record in file 1 to every record in file 2; thus, identifying fields that are shared between the two is critical to keeping the report manageable.

The method of joining files works in concert with the Select records option. For example, say you select Matched with Primary, but your record selection looks for a


specific range of part numbers in file 2. The record selection causes the report to not include any missing records in file 2, which is contrary to the type of join. The result is a report that will not include data from file 1 unless it is also in file 2, making it appear as if you selected the Matched Records method.

Output to a Database File

On the other end of the process, Query has the ability to write data to a physical file. By selecting output type 3 (Database file), you can create a mini-database from any file. The output from one query can then be used as input to another. Linking query output files in a chain can produce reports that are much more complex than any single query could create alone.

As an example, consider how a Query report would count records but exclude any zero values from the count. Given a file containing monthly sales dollars by part number, some months have zero sales because new parts are launched at different times during the year. How do you calculate an average annual sales figure when you can’t just total up all months and divide by 12? With two linked queries!

Figures 1 (page 107) and 2 illustrate how the calculation is performed. The first query reads all nonzero monthly sales records. Use the Select report summary functions panel to specify a Count summary by part number, as well as a total for the Sales column. Sort and break on part number, so the counts are accurate. Then use Select output type and output form to run the report in “summary only” mode, and send the output to a database file in a personal or temporary library. Never use your production libraries, for reasons that will be explained below.

Now, create a second query that uses the output from the first as input. Define a result field that divides the total by the count from the first file. Because the first file includes a break on part number, there is a “break level” column added to its output. Level 1 is the part number summary, and level 0 is the overall report summary. So you will need to include a record selection for BREAKLVL NE ‘0’ to omit the last record, which is a grand total of all the count values. This will report a part’s average sales per year for months where there were sales.

More Links Mean More Power

In addition to joining separate files, Query can also be used to compare a file to itself. For instance, say you have a file that has individual records for each stock location for a part, and you want a report to show any parts that are in more than one location. A single query can’t come up with the list because there’s no way to know if there are multiple locations as it sequentially reads the file. But by using one query to count and summarize multiple locations and a second query to go back to the same file and get the stockroom locations for parts identified by the first, it becomes very easy.

Start with a query that reads all records in the stockroom file, and does a count summary by location. Sort and break on part number and write the output to a new file called COUNTS. Create a second query to link the output from the first with the original file. In the File Select section, enter COUNTS as the primary, and press F9 to add the stockroom file as the secondary. Select 1, matched records, and link the files using the part number. When specifying multiple files, each is given a file ID. The default is T01 for the first file, T02 for the second, and so on. Whenever you want to specify a field anywhere in the query definition and that field name occurs in more than one of the files, you must prefix the field name with the file ID and a period. For instance, if the part number field in the example is called PARTNO, it would have to be referred to by the name T01.PARTNO when referring to the primary file, and T02.PARTNO when referring to the secondary file. In the Select records section, report parts that had a count greater than 1. Also include a selection for BREAKLVL NE ‘0’, as the last record (break level 0) will be the total of all


the count values. This second query will produce a list of only parts that are in multiple locations, with a list of the locations.

The more files that you link together, the more flexibility you have. For instance, when reading individual database records, Query can report the data in rows, but there is no easy way to read and print each record in a separate column. This limitation can be overcome by creating separate query files for each individual column and then a final query that links them all together. Figures 3 and 4 show a report that gives a spreadsheet a run for its money.

Combine Matched and Unmatched Joins

A single Query report can’t display records that are in file A and maybe in B, but not in C. For that matter, neither can most third-party report writer software packages. But, because Query reports can be combined, the difficult task becomes a series of simple steps.

This challenge recently came up when a user wanted to find financial account details, including any monthly budget information, for accounts that have no monthly actuals. The account definitions are in one file, the monthly budget in another, and the monthly actuals in a third. To join the files, the account file is considered the primary file. It must be “matched with primary” to the budget file, and “unmatched with primary” to the actuals. This way, no account record gets dropped if a month is without a budget or actual.

Breaking it down into two queries will get the job done. The first query would “match with primary” to create a list of accounts along with any budget data for those accounts. Write the output of this query to a database file. A second query can be written to use this data file as the primary, joined to the actuals file with the unmatched option. The result is a report that again demonstrates a flexibility that goes beyond the basic file inquiry functionality commonly associated with Query.

Automate the Query Chain

As you’ve seen, there are a few extra steps that need to be taken to get this level of reporting. When using multiple queries, where the output of one is the input to another, it’s more efficient to write a small CL program that’s simply a series of commands rather than have the user run each Query in sequence:

RUNQRY (LIBRARY/QUERY1)
RUNQRY (LIBRARY/QUERY2)
etc.

The CL program approach provides the added benefit of accepting parameters, so calls to different Query sequences can be done automatically based on user input.

Alternatively, if a query has user-dependent selection criteria, you can prompt the operator by using this:

RUNQRY (LIB/QUERY1) +

RCDSLT(*YES)

This displays the record selection screen at runtime. The user can modify the selection criteria for the currently running report, without making permanent modifications to the query definition.

Absolute Power Corrupts!

Warning: Once you go beyond the simple reporting functions of Query and enter the world of file updates, there are some hazards to watch out for. Since Query can overwrite files,
it’s possible to replace your production data with Query output. It’s a handy tool for adding


database records, but this power comes with a higher level of accountability. Be extremely careful when using the replace and append features.

You may feel safer defining QTEMP as the AS/400 file library, so that any output generated by Query is removed from the system when you log out. But even if you are simply writing out to a QTEMP file, if QTEMP is at the top of your library list and you unintentionally named your file the same as a production file (including logical files), your application will start running with the Query data instead of production data. For more protection against the accidental misuse of power, use CRTLIB to create your own library to use for query output.

Finally, linked Query files have the potential to create reports that are enormously large. Ensure that there are sufficient fields defined to join the files, so that a record in one file doesn’t match to every record in a second file.

With a little prudence, this simple report writer can become a powerful data formatter. It’s all in controlling the chain of commands.

Sales Database

Part Month Sales

12-345 1 0.00 12-345 2 0.00 12-345 3 0.00 12-345 4 0.00 12-345 5 0.00 12-345 6 0.00 12-345 7 0.00 12-345 8 0.00 12-345 9 2,000.00 12-345 10 3,000.00 12-345 11 4,000.00 12-345 12 7,000.00

Query 1: Calculate Sales Count and Total

Part Sales Sales

Count Total

12-345 4 16,000

Query 2: Calculate Average Sales

Part Average Sales

12-345 4,000

Figure 1: Use the output from one query as the input to another.


Query 1: Count the number of non-zero records

Specify file selections SALESDB in production library Select records SALES NE 0 Report summary SALES (Total and Count) Define report breaks PART Select output type/form 3 (Database File), 2 (Summary)

Define database file/lib QRYOUT01 / QTEMP, 1 (New File)

Query 2: Calculate average sales

Specify file selections QRYOUT01 in library QTEMP Define result fields AVGSALES = SALES01 / SALES05 Select and sequence fields Seq 10: PART, Seq 20: AVGSALES Select records BREAKLVL NE 0

Figure 2: This definition will produce the report shown in Figure 1.

Query 1: Write 1999 Sales by Part Number to File A

Part Year Sales

12-345 1999 3000 12-346 1999 4000

Query 2: Write 2000 Sales by Part Number to File B

Part Year Sales

12-345 2000 5000 12-346 2000 6000

Query 3: Link File A and File B by Part Number with “Matched with Primary” join.

Part 1999 Sales 2000 Sales

12-345 3000 5000 12-346 4000 6000

Figure 3: Linked queries can combine individual data into columns.


Query 1: Capture 1999 sales

Specify file selections SALESDB in production library Define result field YR = YEAR(SALEDATE) Select and sequence PART, YR, SALES Select records YR EQ 1999 Sort records PART
Report summary SALES (Total) Define report breaks PART, YR (Both at break level 1) Select output type/form 3 (Database File), 2 (Summary) Define database file/lib QRYOUT01 / QTEMP, 1 (New File)

Query 2: Capture 2000 sales

Copy the definition from Query 1, and change only these: Select records YR EQ 2000 Define database file/lib QRYOUT02 / QTEMP, 1 (New File)

Query 3: Link the output into columns by part number

Specify file selections QRYOUT01, QRYOUT02 2 (Matched with Primary)

T01.PART EQ T02.PART Select and sequence T01.PART, T01.SALES, T02.SALES

Figure 4: This definition will produce the report shown in Figure 3.


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: