在条件语句中包装Select语句

时间:2013-09-07 04:39:36

标签: sql-server

为可能有多个结果的select语句的结果创建别名的最佳方法是什么?我尝试过使用Case语句以及If,Then,Else语句,但我在所有实例中都会遇到语法错误。

我的基本代码如下:

Select e.emp_id as 'EmpId'
,pe.name AS 'Goal Plan Name'
,p.id
,(select top 1 (g.statusid) as 'Status' from goals g
inner join goalassignments ga ON ga.goalid = g.id AND g.typeid IN (1,3,5)
where ga.planid = p.id) 

from plans p  
inner join periods (nolock) AS pe on pe.id = p.periodid 
inner join vgr_emp (nolock) AS e on p.empid = e.emp_id  

如果g.statusid = 1那么我希望它显示为“待定” 如果g.statusid = 2那么我希望它显示为“已分配” 但是,有些将为空白,并在列中呈现“Null”。我希望这些价值观能说“没有计划”。

案例陈述是最佳还是if陈述?每一个我尝试我得到语法错误。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

是案例陈述适合您的要求。

尝试以下:

Select e.emp_id as 'EmpId'
,pe.name AS 'Goal Plan Name'
,p.id
,(select top 1 (case when g.statusid=1 then 'Pending' when g.statusid=2 then 'Assigned' when  g.statusid is null then 'No Plan' end) status
from goals g
inner join goalassignments ga ON ga.goalid = g.id AND g.typeid IN (1,3,5)
where ga.planid = p.id) Status
from plans p  
inner join periods (nolock) AS pe on pe.id = p.periodid 
inner join vgr_emp (nolock) AS e on p.empid = e.emp_id

修改

当您告诉我们您的完整标准时,您可以尝试以下方法:

Select e.emp_id as 'EmpId'
,pe.name AS 'Goal Plan Name'
,p.id
,ISNULL((select top 1 (case when g.statusid=1 then 'Pending' when g.statusid=2 then 'Assigned' end) status
from goals g
inner join goalassignments ga ON ga.goalid = g.id AND g.typeid IN (1,3,5)
where ga.planid = p.id),'No Plan') Status
from plans p  
inner join periods (nolock) AS pe on pe.id = p.periodid 
inner join vgr_emp (nolock) AS e on p.empid = e.emp_id

答案 1 :(得分:0)

在mysql中你可以做这样的事情

select concat(if(g.statusid = 1, 'Pending', ''), if(g.statusid = 2, 'Assigned', ''), if(g.statusid is NULL, 'NoPlan', '')), 
e.emp_id as 'EmpId'
,pe.name AS 'Goal Plan Name' ,p.id
    ,(select top 1 (g.statusid) as 'Status' from goals g
    inner join goalassignments ga ON ga.goalid = g.id AND g.typeid IN (1,3,5)
    where ga.planid = p.id) 
from plans p  
inner join periods (nolock) AS pe on pe.id = p.periodid 
inner join vgr_emp (nolock) AS e on p.empid = e.emp_id  

mysql flow control