如何在SQL Server中使用CASE和JOIN语句

时间:2015-12-28 08:57:03

标签: sql-server sql-server-2008 left-join case

我需要从少数几个表中选择一些数据。第一个表包含两列付费代码和付款人代码。根据付费来自,我必须返回学生姓名(来自学生表)或员工姓名(来自员工表)或帐户名(来自帐户表)。截至今天,我在SELECT Query中使用了case语句。我想知道是否可以在LEFT JOIN中这样做。请帮忙!

SELECT  RV.PayerCode ,
        ( SELECT    CASE WHEN PaidFrom = 1
                         THEN ( SELECT  FullName
                                FROM    Students
                                WHERE   StudentID = RV.PayerCode
                              )
                         WHEN paidFrom = 2
                         THEN ( SELECT  AccountName
                                FROM    Accounts
                                WHERE   AccountNumber = RV.PayerCode
                              )
                         WHEN paidfrom = 3 THEN ''
                         WHEN paidFrom = 4
                         THEN ( SELECT  EmployeeName
                                FROM    Employee
                                WHERE   EmployeeID = RV.PayerCode
                              )
                    END
        ) AS PayerName 

FROM    dbo.Finance RV

1 个答案:

答案 0 :(得分:4)

尝试这样的事情

SELECT RV.PayerCode,
       CASE
         WHEN RV.paidfrom = 3 THEN ''
         ELSE COALESCE(s.FullName, a.AccountName, e.EmployeeName)
       END PayerName,
FROM   dbo.Finance RV
       LEFT OUTER JOIN dbo.Students s
                    ON s.StudentID = RV.PayerCode
                       AND RV.PaidFrom = 1
       LEFT OUTER JOIN dbo.Accounts a
                    ON a.AccountNumber = RV.PayerCode
                       AND RV.PaidFrom = 2
       LEFT OUTER JOIN dbo.Employee e
                    ON e.EmployeeID = RV.PayerCode
                       AND RV.PaidFrom = 4 

注意:考虑更改数据库结构