0

为可以有多个结果的 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,那么我希望它显示为“Pending” 如果 g.statusid = 2,那么我希望它显示为“Assigned” 但是,有些会是空白的,它会在列中呈现“Null”。我希望这些价值观说“没有计划”。

最好是 case 语句还是 if 语句?我尝试的每一个都会遇到语法错误。任何帮助,将不胜感激。

4

2 回答 2

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
于 2013-09-07T04:53:47.490 回答
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流量控制

于 2013-09-07T04:48:30.500 回答