联接和案例陈述有帮助

时间:2011-02-21 15:28:25

标签: sql join case

我正在尝试创建一个案例陈述,它将选择系统中每个用户的级别..白金,黄金,白银,铜牌......此查询将进入SSRS报告,其中facilityCode将从下拉列表中选择...我一直在研究案例陈述并理解如何创建一个非常简单的例子,但是我无法使用我的查询来加入它...这是我的首先查询青铜级别。

SELECT XEI.EmployeeId as id, SUM(Credits) , XEI.IsSpouse
FROM Employees E 
JOIN XREFEmployeesInvitations XEI ON E.Id = XEI.EmployeeId 
JOIN Activities A ON XEI.ActivityId = A.Id
JOIN Locations l on l.Id=E.LocationId
JOIN Facilities f on f.Id=l.FacilityId
WHERE   F.Code = COALESCE(@facilityCode, F.Code) 
and E.Id IN (SELECT EmployeeId FROM XREFEmployeesInvitations WHERE ActivityId = 10 ANd IsCompleted = 1)
and XEI.IsCompleted=1
GROUP BY XEI.EmployeeId, XEI.IsSpouse 
HAVING SUM(Credits) between 50 and 99

1 个答案:

答案 0 :(得分:0)

尝试将其包装在另一个投影中,例如

select id, 
"Status" =
        case 
             when credits > 200 and  credits < 300 then 'Silver'  
             when credits > 300 then 'Gold' 
             else 'Bronze'
        end 
        , IsSpouse
from (
    SELECT XEI.EmployeeId as id, SUM(Credits) as credits , XEI.IsSpouse as IsSpouse
    FROM Employees E 
    JOIN XREFEmployeesInvitations XEI ON E.Id = XEI.EmployeeId 
    JOIN Activities A ON XEI.ActivityId = A.Id
    JOIN Locations l on l.Id=E.LocationId
    JOIN Facilities f on f.Id=l.FacilityId
    WHERE   F.Code = COALESCE(@facilityCode, F.Code) 
    and E.Id IN (SELECT EmployeeId FROM XREFEmployeesInvitations WHERE ActivityId = 10 ANd IsCompleted = 1)
    and XEI.IsCompleted=1
    GROUP BY XEI.EmployeeId, XEI.IsSpouse 
    HAVING SUM(Credits) between 50 and 99
)