If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > SQL Advice

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-28-05, 10:40
ek1975 ek1975 is offline
Registered User
 
Join Date: Sep 2003
Posts: 44
SQL Advice

DB2 V7.2 on z/OS:

Hello, I got one of those SQL's where I have figured the way to get the data I want, but I am not sure, whether it's the best way: The table consists of 12 date fields (d1,d2,d3.....), The user would enter a date range (start and end dates) and I have to display the date column along with the number of rows matched within the user specified date range like:

d1 51
d2 31
....

The way I figured to do this is:
select 'd1', count(*) from t1 where d1 between :h1 and :h2
union all
select 'd2', count(*) from t1 where d2 between :h1 and :h2....

Is there a better way to do this and avoid those multiple passes..... it's not UDB and I can't do those COUNT OVER()....
Thanks in advance
Reply With Quote
  #2 (permalink)  
Old 02-28-05, 12:23
Wim Wim is offline
Registered User
 
Join Date: Nov 2004
Posts: 1,279
I think you should normalise your table with the 12 date fileds.
nr_row maps the 12 records in the normalised table to one row of the original table, nr_d_column is the number of the d column in the original table (d1 is 1, d2 is 2, ..., d12 is 12)
Code:
CREATE TABLE t (
  nr_row       INTEGER  NOT NULL,
  nr_d_column  SMALLINT NOT NULL,
  d            DATE     NOT NULL,
  CONSTRAINT pk_t PRIMARY KEY (nr_row, nr_d_column)
)

SELECT 'd'||CHAR(nr_d_column),
        COUNT(*)
FROM t1
WHERE d BETWEEN :h1 AND :h2
ORDER BY nr_row, nr_d_column
In this case, your users will only get a record back when there is at least 1 match.

If they want a record, even when the result is 0, you could use:
Code:
SELECT 'd'||CHAR(nr_d_column),
       SUM(CASE WHEN d BETWEEN :h1 AND :h2
                THEN 1
                ELSE 0
            END)
FROM t1
ORDER BY nr_row, nr_d_column
Perhaps someone knows a more elegant way for this last query.

Wim
Reply With Quote
  #3 (permalink)  
Old 02-28-05, 14:00
ek1975 ek1975 is offline
Registered User
 
Join Date: Sep 2003
Posts: 44
Wim: modifying the table design is out of the question here, too many programs will have to be changed....

sum(case...) does give a much better performance though, didn't think it would work on z/OS; but it does.
Thanks
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On