在select语句中使用了已连接的表

时间:2011-08-04 20:07:24

标签: sql join case

我想知道在声明select语句中的列时是否可以在CASE语句中使用绑定的连接表。我在下面的代码段中包含了我的问题的简化示例。任何想法?谢谢!

SELECT  M.MID 
    ,[Count] =  CASE (SELECT COUNT(*) FROM Refund R2 
            WHERE R2.RefundID = R.RefundID) = 1
                        THEN 'One'
                        ELSE 'Many'
                        END

FROM #temp T
JOIN Refund R ON R.RefundID = T.RefundID

“WHERE R2.RefundID = R.RefundID表示”R.RefundID无法绑定。

2 个答案:

答案 0 :(得分:1)

你的别名不好。您有R但不是R2,引用了:

SELECT  M.MID 
        ,[Count] =  CASE WHEN (SELECT COUNT(*) FROM ReferralTypeKey R2
                               WHERE R2.RefundID = R.RefundID) = 1
                               THEN 'One'
                               ELSE 'Many'
                               END

FROM #temp T
JOIN Refund R ON R.RefundID = T.RefundID

答案 1 :(得分:1)

如果您使用的是SQL Server 2005或更高版本,则可以尝试不同的方法:

SELECT
  M.MID, 
  [Count] = CASE COUNT(*) OVER (PARTITION BY R.RefundID)
    WHEN 1 THEN 'One'
    ELSE 'Many'
  END
FROM #temp T
JOIN Refund R ON R.RefundID = T.RefundID