创建为Case的列当结果不在where子句中时

时间:2017-01-30 10:18:06

标签: sql sql-server

我正在尝试根据动态创建的列过滤值但不起作用,请帮我继续。

SELECT proj.is_active,pal.Project_Artifact_Id,
       CASE WHEN pal.artifact_status IN ('Closed', 'Verified','Rejected')
                THEN  'COM'
            WHEN pal.artifact_status IN ('In Progress') 
                 AND (pal.due_date = getDate() OR pal.due_date = (Getdate()+2))
                THEN  'OD'
            WHEN pal.artifact_status IN ('In Progress') AND pal.due_date > (Getdate()+2)
                THEN  'CR'
       END AS Filter_Status
FROM Project_Artifact_List pal,
     Projects proj 
WHERE proj.project_code = pal.Project_Code
  AND Filter_Status IN ('CR');

更新

invalid column name error message comes

3 个答案:

答案 0 :(得分:4)

您无法访问where子句中的列别名。首先将您的查询包装在派生表中:

select *
from
(  
    SELECT proj.is_active,pal.Project_Artifact_Id,
           CASE WHEN pal.artifact_status IN ('Closed', 'Verified','Rejected')
                    THEN  'COM'
                WHEN pal.artifact_status IN ('In Progress') 
                     AND (pal.due_date = getDate() OR pal.due_date = (Getdate()+2))
                    THEN  'OD'
                WHEN pal.artifact_status IN ('In Progress') AND pal.due_date > (Getdate()+2)
                    THEN  'CR'
           END AS Filter_Status
    FROM Project_Artifact_List pal,
         Projects proj 
    WHERE proj.project_code = pal.Project_Code    
) dt
WHERE Filter_Status IN ('CR');

答案 1 :(得分:2)

 this.today = new Date();
    this.tommorowDate =this.today.setDate(this.today.getDate() + 1)
    console.log(this.tommorowDate)
    this.dd = this.today.getDate();
    this.mm = this.today.getMonth()+1;
    this.yyyy = this.today.getFullYear();
    this.currentDate = this.dd+'/'+this.mm+'/'+this.yyyy;

 for(var i = 1; i <= 3; i++){
       var incrementdate = this.dd+i;
        this.datepickerArray.push(this.yyyy+'-'+this.mm+'-'+incrementdate)

    }

答案 2 :(得分:1)

CASE仅依赖于Project_Artifact_List,您可以使用CROSS APPLY来计算Filter_Status,以便在WHERE中识别

SELECT proj.is_active,pal.Project_Artifact_Id,       
FROM Project_Artifact_List pal
CROSS APPLY (SELECT
           CASE WHEN pal.artifact_status IN ('Closed', 'Verified','Rejected')
                THEN  'COM'
            WHEN pal.artifact_status IN ('In Progress') 
                 AND (pal.due_date = getDate() OR pal.due_date = (Getdate()+2))
                THEN  'OD'
            WHEN pal.artifact_status IN ('In Progress') AND pal.due_date > (Getdate()+2)
                THEN  'CR'
       END AS Filter_Status) fs 
   , Projects proj
WHERE proj.project_code = pal.Project_Code
  AND fs.Filter_Status IN ('CR');