简体   繁体   中英

MySQL CASE from another CASE result in SQL query

I have a fairly large query one part of which is:

... 
ROUND(AVG( 
  CASE RA12.answer
    WHEN 'L' THEN 3
    WHEN 'P' THEN 2
    WHEN 'E' THEN 1
    ELSE 0
  END
),0) as 'avg_presentation_format_raw'
...

...and it all works fine including the column above. What I now need to do is another CASE (or something) on the results of the column above. However since it's calculated at run time I cannot reference it. I am guessing I need to use temp variables or something and I found a few things that come close, but nothing that quite does what I am looking for.

What I need is something like what is below based on and in addition to the calculated column above:

...  
  CASE avg_presentation_format_raw <--THIS WON'T WORK BECAUSE IT'S THE CALCULATED COLUMN
    WHEN 3 THEN 'Lecture'
    WHEN 2 THEN 'Poster'
    WHEN 1 THEN 'Either'
    ELSE 'Not Specified'
  END as 'presentation_format'
...

Any thoughts or ideas appreciated!

TIA

Use subquery like:

SELECT 
    CASE t.avg_presentation_format_raw 
       WHEN 3 THEN 'Lecture'
       WHEN 2 THEN 'Poster'
       WHEN 1 THEN 'Either'
       ELSE 'Not Specified'
    END AS 'presentation_format'
    (...)
FROM 
(
   SELECT ROUND(AVG( 
       CASE RA12.answer
          WHEN 'L' THEN 3
          WHEN 'P' THEN 2
          WHEN 'E' THEN 1
          ELSE 0
       END),0) AS 'avg_presentation_format_raw'
       (...)
    FROM (...)
) AS t

Or just wrap it:

SqlFiddleDemo

SELECT
  CASE ROUND(AVG( 
      CASE answer
         WHEN 'L' THEN 3
         WHEN 'P' THEN 2
         WHEN 'E' THEN 1
         ELSE 0
      END
      ),0)
    WHEN 3 THEN 'Lecture'
    WHEN 2 THEN 'Poster'
    WHEN 1 THEN 'Either'
    ELSE 'Not Specified'
  END as 'presentation_format',
  ROUND(AVG( 
   CASE RA12.answer
      WHEN 'L' THEN 3
      WHEN 'P' THEN 2
      WHEN 'E' THEN 1
      ELSE 0
   END),0) AS 'avg_presentation_format_raw'
FROM tab

But you cannot reference like this:

SELECT 
   1 AS 'var1'
   var1 + 1 AS 'var2'

All the results of a single row from a select are atomic. That is, you can view them all as if they occur in parallel and cannot depend on each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM