Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2008
    Posts
    5

    Unanswered: problems grouping with a case statement

    Hi everyone, this is my first post so go easy on me!!
    I'm relatively new to the DB2 world and am having a bit of an SQL problem.

    Basically, i'm struggling to goup by the result of a case statement..

    Here's the case statement:
    Code:
    (CASE WHEN PROD.PROB_DFLT_PCT_RES IS NOT NULL THEN PROD.PROB_DFLT_PCT_RES * 100
    WHEN PROD.PRBL_DFLT_PCT IS NOT NULL THEN PROD.PRBL_DFLT_PCT
    ELSE IP.PROB_DFLT_PCT END) AS PD_PCT
    this gives me a number that's actually a dimension, when i include it in my group by i get an error:

    Code:
    SQL0206N  "PD_PCT" is not valid in the context where it is used
    Can anybody help me find a way around this?

  2. #2
    Join Date
    Jun 2003
    Location
    Toronto, Canada
    Posts
    5,516
    Provided Answers: 1
    Quote Originally Posted by drsmyth

    Can anybody help me find a way around this?
    You cannot use the new column alias (PD_PCT) in the same subselect where it is defined; put the entire case statement in the GROUP BY clause.
    ---
    "It does not work" is not a valid problem statement.

  3. #3
    Join Date
    Sep 2004
    Location
    Belgium
    Posts
    1,126
    Or place the CASE expression in a nested select:
    Code:
    SELECT PD_PCT, COUNT(*), ...
    FROM (SELECT ..., 
                 CASE WHEN PROD.PROB_DFLT_PCT_RES IS NOT NULL
                      THEN PROD.PROB_DFLT_PCT_RES * 100
                      WHEN PROD.PRBL_DFLT_PCT IS NOT NULL
                      THEN PROD.PRBL_DFLT_PCT
                      ELSE IP.PROB_DFLT_PCT END AS PD_PCT
          FROM PROD INNER JOIN IP ON ...) X
    GROUP BY X.PD_PCT
    --_Peter Vanroose,
    __IBM Certified Database Administrator, DB2 9 for z/OS
    __IBM Certified Application Developer
    __ABIS Training and Consulting
    __http://www.abis.be/

  4. #4
    Join Date
    Sep 2004
    Location
    Belgium
    Posts
    1,126
    Or even slightly shorter (and more readable?):
    Code:
    SELECT PD_PCT, COUNT(*), ...
    FROM (SELECT ..., 
                 COALESCE(PROD.PROB_DFLT_PCT_RES * 100,
                          PROD.PRBL_DFLT_PCT,
                          IP.PROB_DFLT_PCT)     AS PD_PCT
          FROM PROD INNER JOIN IP ON ...) X
    GROUP BY X.PD_PCT
    --_Peter Vanroose,
    __IBM Certified Database Administrator, DB2 9 for z/OS
    __IBM Certified Application Developer
    __ABIS Training and Consulting
    __http://www.abis.be/

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •