我无法在嵌套选择中使用CASE语句。我想我很接近,但我不能完全正确地理解语法。到目前为止,我已经尝试过:
SELECT l.*,
Credit = (
CASE WHEN ISNULL(M.POSTCODE,'') <> '' THEN
sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4)
ELSE
sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4)
END
)
FROM live l INNER JOIN master m on m.ClientID = L.ClientID
WHERE ClientID = 12345
还有:
SELECT l.*,
(SELECT
CASE WHEN ISNULL(M.POSTCODE,'') <> '' THEN
sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4)
ELSE
sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4)
END
) AS Credit
FROM live l INNER JOIN master m on m.ClientID = L.ClientID
WHERE ClientID = 12345
这似乎与http://msdn.microsoft.com/en-us/library/ms181765.aspx的MSDN示例相匹配。我错过了什么吗?
答案 0 :(得分:1)
我认为你需要在sum子查询之前添加一些选择。
SELECT l.*,
Credit = (
CASE WHEN ISNULL(M.POSTCODE,'') <> '' THEN
(SELECT sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4))
ELSE
(SELECT sum(Credit) from Balance cb Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4))
END
)
FROM live l
INNER JOIN master m on m.ClientID = L.ClientID
WHERE ClientID = 12345
您的选择也完全相同,因此除非您打算让它们与众不同,否则不需要案例。
答案 1 :(得分:0)
SELECT l.*,
CASE
WHEN ISNULL(M.POSTCODE,'') <> '' THEN
(SELECT sum(Credit)
from Balance cb
Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4))
ELSE
(SELECT sum(Credit)
from Balance cb
Where LEFT(LTrim(cb.AccountHolder),4) LIKE LEFT(LTrim(m.Company),4) )
END as 'Credit'
FROM live l INNER JOIN master m
on m.ClientID = L.ClientID
WHERE ClientID = 12345