我试图改进以下CASE语句,只计算一次差异。我这样做是为了避免负数:
SELECT (CASE WHEN ((SELECT 100 - (SELECT COUNT(CustomerId) FROM Customers)) > 0)
THEN (SELECT 100 - (SELECT COUNT(CustomerId) FROM Customers))
ELSE (0)
END)
这不仅看起来很愚蠢,而且也不是线程安全的。我尝试了以下操作,但是收到错误消息“无效的列名'diff'。”
SELECT (CASE WHEN ((SELECT 100 - (SELECT COUNT(CustomerId) FROM Customers) as diff) > 0)
THEN (diff)
ELSE (0)
END)
如何简化?是否有内置的SQL函数已经完成这项工作?
编辑:抱歉,忘记提及select语句在视图声明中,所以我无法声明变量。
答案 0 :(得分:2)
DECLARE @diff int
SELECT @diff = 100 - COUNT(*) FROM Customers
SELECT CASE WHEN @diff > 0 THEN diff
ELSE 0
END as Diff
答案 1 :(得分:2)
如果我遵循你的逻辑,那就应该这样做:
SELECT COALESCE ((SELECT 100 - COUNT(CustomerID)
FROM Customers
HAVING COUNT(CustomerID) < 100), 0)
略微更优雅。
如果有基于行的MAX()函数,我们也可以使用它。当然,你可以轻松地写一个。
答案 2 :(得分:1)
您可以使用变量来启动查询结果,这样您就不必执行两次。例如:
DECLARE @CustomerCount INT
SELECT @CustomerCount = COUNT(CustomerId) FROM Customers
SELECT CASE WHEN (100 - @CustomerCount > 0)
THEN 100 - @CustomerCount
ELSE (0)
END
答案 3 :(得分:1)
你是对的,你只想算一次,你想要这样做,这样就可以清楚地表明你的逻辑是什么。
SELECT CASE WHEN cnt > 100 THEN 0
ELSE 100 - cnt END AS diff
FROM (SELECT COUNT(1) AS cnt
FROM Customers) AS CustomerCnt