28
Thu, Nov
0 New Articles

Fun with Dates

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

Date, time, and timestamp data types are often overlooked and underused in AS/400 information systems. This article, illustrated with practical examples, gives you a glimpse of the power available to you by using these data types (instead of numeric and character fields) to store time. You’ll learn how to do date math, how to handle durations of time, and how to circumvent some limitations of SQL/400.

The date, time, and timestamp data types and scalar functions are probably the most overlooked and underused functions in DB2/400. That’s too bad. There’s so much you can do with them that you can’t do with numeric and character date fields. You can add them, subtract them, and generally abuse them to your heart’s content and the benefit of your organization. In this article, I’ll show you some neat tricks that you can put to work in your environment.

 

The Nitty-gritty

 

The AS/400 has scalar functions that accept dates or date expressions as arguments. A scalar function is an SQL function that can be used in an SQL query anywhere that an expression can be used. Month is an example of a scalar function. Month returns the integer month portion of a date or timestamp column or expression. (Complete documentation of both the AS/400 and ODBC scalar functions can be found on my Web site, www.sqlthing.com/ODBCInfo.htm.

 

Your First Date

 

For the purposes of the following example queries, assume that you have a table (file) called WEBHITS that has the columns (fields) WEBPAGE and TMSTP. Each time a page is hit on your Web server, an entry recording the page and current timestamp is made. On your first date, management has decided that they want to know the number of page hits by day of the week. To get the data will necessitate using the DayofWeek scalar function.

The DayofWeek function takes a date or timestamp expression and returns a number between 1 and 7 in which 1 represents Sunday and 7 represents Saturday. This can be a useful method for indicating the day of week to a report user, but then you have to train the users that 1 represents Sunday, 2 represents Monday, and so on. By combining the DayofWeek function with the Substring function, you can return a string representing

the day of the week. The query illustrated in Figure 1 would return the page name and day of week from the WEBHITS table.

Now, I’ll dissect the function. The statement reads a record that has a date of 01/01/1980, which was a Tuesday, so the DayofWeek function returns a 3. Since 3*3 = 9, the Substring function starts at the ninth character and returns the next three characters. This results in the string TUE, and (magic!) you can now read the table, summarize the results, and create management’s report.

The above example is satisfying in and of itself, but I am extremely lazy. I don’t want to read all of those records and make my own summarization. To get SQL to summarize this for me, I need the Group By clause.

Unfortunately, the AS/400 will not allow you to use Group By with expressions or derived columns. It will allow you to group by scalar functions if you hide them in a view. (DB/2 Universal allows grouping by derived columns. Perhaps someday this ability will exist in DB2/400. To group by a scalar, I will create a view over the WEBHITS table, as shown in Figure 2.

The select statement uses the Month scalar (which returns the integer month number from a date or timestamp expression) and the trusty DayofWeek function to make a view called WEBTEMP. WEBTEMP contains one record for each record in the WEBHITS table and has the columns PAGE, MN, and DOW. I can now fool the AS/400 with the statement shown in Figure 3, which produces the information shown in Figure 4.

Of course, this shows a problem with the day-of-week dodge: It doesn’t sort correctly! Humans want to see MON, TUE, WED, etc. To correct this, I can change the day-of-week formula to the following:

SUBSTRING (‘XXXX1-SUN2-MON3-TUE4-WED5-THR6-FRI7-SAT’, DAYOFWEEK(TMSTP) *5, 5)

The days of the week will be returned as 1-SUN, 2-MON, 3-TUE, and so on. Even though this may not be as pleasing as MON, TUE, WED, at least it’s in order.

 

Temporal Increments (Dr. Who?)

 

Once you open Pandora’s date box, the powers that be will come up with an inexhaustible set of reports that are temporally challenged. Suppose, for example, that you’re asked to determine the number of page hits per quarter hour. First, you need to create a view over the WEBHITS table, as shown in Figure 5. The view should include time of day by the quarter hour.

Converting a time of day to an exact quarter hour requires the Substring, Digits, Integer, Hour, and Minute scalar functions. Hour returns the hour part of a timestamp, and Minute returns the minute portion. Integer forces a decimal result to be truncated. If the value of TMSTP is 01/01/1980 08:17:30.000099, the formula performs the steps shown in Figure 6.

I can now group by the HRINC column, as the query in Figure 7 does, to report on activity by 15-minute increments. I get a result like that shown in Figure 8.

 

Date Math!

 

Did you know that SQL has built-in support for date math? You can use the Days, Weeks, Months, Years, Hours, Minutes, Seconds, or Microseconds keywords to add or subtract periods of time from date, time, and timestamp type columns. The keywords can be used anywhere in an SQL statement that it is legal to use an expression.

Here is a practical use of the Day keyword. Using the WEBHITS example table, the query in Figure 9 would find pages hit within 60 days of the current date (when the query executes).

 

What’s a Duration?

 

Dates, times, and timestamps can also be added and subtracted from each other. The result of such an operation is something truly awful called duration. Duration represents the temporal difference in years, months, days, hours, minutes, seconds, and

microseconds. IMHO, the operations should result in a floating-point number in which the left-hand portion is the number of days’ difference and the right-hand portion is the number of microseconds’ difference. In this manner, you are open to all kinds of neat date and time tricks. However, one takes what one gets, and durations still allow for a lot of stupid date tricks. Before I play any more tricks with durations, however, let me show you how they are returned.

If the operands are both dates, the duration returned is a date duration of decimal (8,0). The first 4 bytes represent the number of years between the dates, the next 2 bytes represent the number of months between dates, and the last 2 bytes represent the number of days between the operands.

Time durations occur only when both operands are time type columns. A time duration is a decimal (6,0) number in which the first 2 bytes represent hours, the next 2 bytes represent minuets, and the last 2 bytes represent seconds.

A timestamp duration is a decimal (20,6) number, which is the combination of a date duration concatenated with a time duration. The six digits to the right of the decimal place represent the number of microseconds between the durations.

OK, so now you know all about the formatting of durations: What does this knowledge buy you? Not much, but knowledge for its own sake is a good thing. If you absolutely must add or subtract dates and times from each other, at least you now know what the AS/400 is doing with the information.

Here is a trick I apply to calculate the computing minutes that an employee used yesterday. Our employees enter records, and each record has a timestamp column called DTEIN; the employee’s initials are in the column OPERNO. The query (see Figure 10) uses the max and min functions to get the first and last timestamp seen for each employee. When min(dtein) is subtracted from max(dtein), the result is a timestamp duration. I use the Hour, Minute, and Second scalar functions to retrieve the relevant parts of the duration for manipulation. The query returns a table like the one shown in Figure 11. Here is a vivisection of the formula:

At the outset, Second( max(dtein) - Min(dtein)) returns the number of the seconds part of the timestamp duration. Seconds are then divided by (60*1.00), which is a dodge to get a decimal number. The Seconds function returns an integer, and 60 is an integer. Therefore, you must force the number 60 to be cast as a floating-point number, hence the 60*1.00, or the AS/400 will perform integer arithmetic and truncate any remainder. If the remainder is truncated, you lose your decimal seconds.

Next, the Minute function is used to return the minute duration between the minimum and maximum DTEIN values.

Finally, the Hour function is used to return the hours duration and multiplies the duration by 60 to achieve number of minutes. Adding the minutes together with the seconds yields the minutes and seconds of computer time that our operator used.

 

That’s Not All, Folks...

 

I hope that you have gained a new appreciation for the DB2/400 date, time, and timestamp data types from this little exploration. Be sure to check out DB2 for AS/400 SQL Programming or my Web page for more information on the other date and timestamp scalar functions. Remember that dates can be fun!

 

References

 

DB2 for AS/400 SQL Programming (SC41-5611, CD-ROM QB3AQ801) DB2 for AS/400 SQL Reference (SC41-5612, CD-ROM QB3AQ901)

Select WEBPAGE,

substring('XXSUNMONTUEWEDTHRFRISAT', dayofweek(TMSTP)*3, 3)

from SQLEXAMP.WEBHITS

Figure 1: Converting a number to the abbreviation of a day of week

CREATE VIEW SQLEXAMP.WEBTEMP (PAGE, MN, DOW) as

Select WEBPAGE, Month(TMSTP),

SUBSTRING('XXSUNMONTUEWEDTHRFRISAT', DAYOFWEEK(TMSTP) * 3, 3)

From SQLEXAMP.WEBHITS

Figure 2: Creating a view allows you to group by scalar functions

Select PAGE, MN, DOW, COUNT(*)

from SQLEXAMP.WEBTEMP

GROUP BY PAGE, MN, DOW

Figure 3: Grouping by a view

WEBPAGE Month Day of Week Hits

INDEX 1 FRI 111

INDEX 1 TUE 563

INDEX 1 WED 654

INDEX 2 THR 421

INDEX 2 WED 221

Figure 4: Query Results using the DayofWeek and Month functions

CREATE VIEW SQLEXAMP.WEBTEMPA (PAGE, MN, DOW, HRINC) as

Select WEBPAGE, Month(TMSTP),

substring('XXSUNMONTUEWEDTHRFRISAT', DAYOFWEEK(TMSTP) * 3, 3) ,

substring(digits((hour(TMSTP)*100) + (integer(minute(TMSTP)/15)*15)),7,4)
from SQLEXAMP.WEBHITS

Figure 5: Creating a view is sometimes necessary for building complex queries

hour(TMSTP)*100 = 800
integer(minute(TMSTP)/15)*15 = 15
800+15 = 815

Digits(815) = '0000000815'
substring('0000000815',7,4) = '0815'

Figure 6: Converting a time of day to an exact quarter hour

SELECT PAGE, HRINC, COUNT(*)

from SQLEXAMP.WEBTEMPA

group by PAGE,HRINC

order by PAGE,HRINC

Figure 7: Reporting Web hits in 15-minute intervals

PAGE HRINC COUNT(*)

INDEX 0815 637 INDEX 0830 921 INDEX 0845 910 INDEX 0900 54

Figure 8: Breaking a timestamp column into day parts

Select WEBPAGE, COUNT(*)

from EXAMPSQL.WEBHITS

where TMSTP BETWEEN CURRENT_TIMESTAMP - 60 DAYS

AND CURRENT_TIMESTAMP

GROUP BY WEBPAGE

Figure 9: SQL makes easy work of date and time arithmetic

SELECT OPERNO,
( (second ( max(dtein)- min(dtein) ) ) / (60*1.00 ) )
+ Minute( max(dtein)- min(dtein) )
+ (hour( max(dtein) - min(dtein) ) * 60) as T from SQLEXAMP.EMPRECS
where DATE(DTEIN)=CURRENT_DATE - 1 DAY
Group by OPERNO

Figure 10: Making sense of timestamp durations

OPERNO Minutes

ANN 169.45 BILL 142.21 TIM 131.55

Figure 11: Timestamp durations have been converted to minutes

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: