如何使用UNION组合三个选择语句

时间:2014-02-13 06:33:19

标签: sql sql-server-2008

我使用以下查询进行组合以获得不同的结果。我结合前两个选择查询我需要将第三个选择查询与前两个查询组合。请提出您的想法。

我的查询是:

Select distinct Emp.EmpID,Emp.HolderName,jobprf.pkprofileid,
                    CASE WHEN jobprf.isSelfEvaluvated=1 THEN 'EVAL' ELSE 'NOTEVAL' END as Evalue,
                    CASE WHEN jobprf.isSelfEvaluvated=0  THEN 'Self Evaluvation Pending' ELSE 'Self Evaluvated' END as selfeval,
                    CASE WHEN jobprf.isMgEvaluvated=0 THEN 'Manger Evaluvation Pending' ELSE 'Manager Evaluvated' END as mangeval
         from tblEmpRegistration Emp inner join  tbljobprofile jobprf on Emp.EmpID=jobprf.EmpID  where Emp.EmpID=@Mangrid or Emp.ManagerID=@Mangrid  and jobprf.RaterID<>@Mangrid 

        UNION All

        Select distinct Emp.EmpID,Emp.HolderName,Emp.CompanyID,Emp.HolderName,
            CASE WHEN Emp.EmpID IS NOT NULL THEN 'Self Evaluvation Pending' ELSE 'Self Evaluvated' END as selfeval,
            CASE WHEN Emp.EmpID IS NOT NULL THEN 'Manger Evaluvation Pending' ELSE 'Manager Evaluvated' END as mangeval
        from tblEmpRegistration Emp where Emp.EmpID NOT IN(SELECT EmpID FROM tbljobprofile) AND Emp.TITLE<>2 order by Emp.EmpID

        UNION All

        Select pkprofileid,isSelfEvaluvated,isMgEvaluvated,isMgEvaluvated,isMgEvaluvated,isMgEvaluvated from tbljobprofile where RaterID=@Mangrid 

它显示错误

  

关键字“UNION”

附近的语法不正确

2 个答案:

答案 0 :(得分:2)

您不能在UNION子句中使用ORDER BY子句。

答案 1 :(得分:1)

如果所有选择查询以相同的顺序返回相同的列集,你可以联合。!! 并且在你的情况下列集和顺序不一样,所以它会抛出一个错误