Domanda

Sometimes my queries have long case when statements. For example,

CASE WHEN BASE_YM = TO_CHAR(DEFAULT_YM,            'YYYYMM') THEN '00'
     WHEN BASE_YM = TO_CHAR(DEFAULT_YM - 1 MONTHS, 'YYYYMM') THEN '01'
     WHEN BASE_YM = TO_CHAR(DEFAULT_YM - 2 MONTHS, 'YYYYMM') THEN '02'
     .
     .
     .
     WHEN BASE_YM = TO_CHAR(DEFAULT_YM - 35 MONTHS, 'YYYYMM') THEN '35'
     WHEN BASE_YM = TO_CHAR(DEFAULT_YM - 36 MONTHS, 'YYYYMM') THEN '36'

This case when statement itself takes up 37lines and I was wondering if there might be maybe a way to shorten the case when statement by using i=00, ..., 36 something like that?

È stato utile?

Soluzione

It seems like all you're really doing is finding out how many months are between BASE_YM and DEFAULT_YM, and making that a character type. I think the same result can be retrieved by doing some date math (and I'm guessing it'd be more efficient, because it wouldn't have to calculate up to 36 different TO_CHAR calls) This whole statement would replace the CASE. I tested similar logic on DB2 for Linux/Unix/Windows v.9.7, and z/OS v10:

SELECT 
    LPAD(
        ABS(
            MONTH(
                TIMESTAMP_FORMAT(BASE_YM, 'YYYYMM') - 
                DEFAULT_YM
            )
        )
    ,2,'0')
FROM your_table

I added the extra spacing so that you could (hopefully) follow along a little easier. Basically, it just subtracts DEFAULT_YM from the converted form of BASE_YM. Then, I take the Absolute Value of the difference in months, and then convert it to a zero-padded character field.

Altri suggerimenti

make a new table with 2 columns containing your 36 rows of distinct values, then join it on? this will eliminate the need for a case statement at all

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top