来自另一个CASE的MySQL CASE导致SQL查询

时间:2015-09-06 16:32:18

标签: mysql sql

我有一个相当大的查询,其中一部分是:

...  
  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'
...

......一切正常,包括上面的专栏。我现在需要做的是上面一栏结果的另一个案例(或其他)。但是因为它是在运行时计算的,所以我无法引用它。我猜我需要使用临时变量或其他东西,我发现了一些接近的东西,但没有什么能完全符合我的要求。

除了上面的计算列之外,我需要的是以下内容:

let partial = self.partialPlaylists[indexPath.row] as! SPTPartialPlaylist
        SPTPlaylistSnapshot.playlistWithURI(partial.uri, accessToken: self.session.accessToken, callback: {(error: NSError!, result: AnyObject!) -> Void in
            let snapshot = result as! SPTPlaylistSnapshot
            playListVC.snapshot = snapshot
            playListVC.currentPage = snapshot.firstTrackPage
            playListVC.partialPlaylist = partial
            playListVC.session = self.session
            self.navigationController?.pushViewController(playListVC, animated: true)
        })

赞赏任何想法或想法!

TIA

1 个答案:

答案 0 :(得分:2)

使用子查询,如:

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

或者只是包装它:

<强> 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

但是你不能这样引用:

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

select中单行的所有结果都是原子的。也就是说,您可以将它们全部视为并行发生,不能相互依赖。