案例sql列计算

时间:2013-04-26 05:34:02

标签: mysql sql

我正在尝试计算作为列,但似乎失败了。没有名为gap

的列

该行是

case d.gap when  a.actual_value IS TRUE then (quar_target - a.actual_value) else 'NULL' END ,

整个脚本是

SELECT    
    weekly.* ,
    quarterly.target_value as quar_target
FROM  ( 
    SELECT a.week_id,
           d.region_id,
           d.region_name,
           d.metric_id  ,
           case d.metric_desc 
               when 'BE GMV Lift' then 'GMV Lift'
               when 'B2C GMV Lift' then 'GMV Lift' 
               when 'Trust GMV Lift' then 'GMV Lift' 
               else d.metric_desc
           end as metric_desc,
           case d.gap 
               when  a.actual_value IS TRUE 
                   then (quar_target - a.actual_value) 
                else 'NULL' END,
           d.ini_name     ,
           a.actual_value ,
           a.actual_txt   ,
           a.target_value ,
           a.target_txt   ,
           a.signals       ,
           a.comments                       
    FROM       
       -- Get  most recently reported records. If the metric is not reported for this week, get the last reported number 
        ( SELECT  *
          FROM    l1_weekly_entry   
          WHERE week_id=WEEK(CURDATE(), 1) - 1
        )   a    

我正在尝试引入一个列d.gap

2 个答案:

答案 0 :(得分:0)

在答案中的许多地方,您忘记写END的案例。 例如

case d.gap when  a.actual_value IS TRUE then (quar_target - a.actual_value) else 'NULL' END

同样。

<强> MSDN:

http://msdn.microsoft.com/en-us/library/ms181765.aspx

使用Exmple的语法:

http://blog.sqlauthority.com/2007/04/14/sql-server-case-statementexpression-examples-and-explanation/

答案 1 :(得分:0)

我得到的是你想要一个新的gapd,你可以在选择列表中这样介绍

..., gap = (case when  a.actual_value IS TRUE 
                   then (quar_target - a.actual_value) 
                else 'NULL' END), ...

您不能引入包含d.gap等别名的列,因为它不属于任何表。

所以你的完整查询就像这样

SELECT    
    weekly.* ,
    quarterly.target_value as quar_target
FROM  ( 
    SELECT a.week_id,
           d.region_id,
           d.region_name,
           d.metric_id  ,
           case d.metric_desc 
               when 'BE GMV Lift' then 'GMV Lift'
               when 'B2C GMV Lift' then 'GMV Lift' 
               when 'Trust GMV Lift' then 'GMV Lift' 
               else d.metric_desc
           end as metric_desc,
           gap = case when  a.actual_value IS TRUE 
                   then (quar_target - a.actual_value) 
                else 'NULL' END,
           d.ini_name     ,
           a.actual_value ,
           a.actual_txt   ,
           a.target_value ,
           a.target_txt   ,
           a.signals       ,
           a.comments                       
    FROM       
       -- Get  most recently reported records. If the metric is not reported for this week, get the last reported number 
        ( SELECT  *
          FROM    l1_weekly_entry   
          WHERE week_id=WEEK(CURDATE(), 1) - 1
        )   a

同样适用于d.metric_desc,因为此列位于您的表格中