How can you use COUNT() in a comparison in a SELECT CASE clause in Sql Server?
-
21-07-2021 - |
Вопрос
Let's say you want do something along the following lines:
SELECT CASE
WHEN (SELECT COUNT(id) FROM table WHERE column2 = 4) > 0
THEN 1 ELSE 0 END
Basically just return 1 when there's one or more rows in the table, 0 otherwise. There has to be a grammatically correct way to do this. What might it be? Thanks!
Решение
You could do this:
SELECT CASE WHEN COUNT(ID) >=1 THEN 1 WHEN COUNT (ID) <1 THEN 0 END FROM table WHERE Column2=4
Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Другие советы
Question: return 1 when there's one or more rows in the table, 0 otherwise:
In this case, there is no need for COUNT
. Instead, use EXISTS
, which rather than counting all records will return as soon as any is found, which performs much better:
SELECT CASE
WHEN EXISTS (SELECT 1 FROM table WHERE column2 = 4)
THEN 1
ELSE 0
END
Mahmoud Gammal posted an answer with an interesting approach. Unfortunately the answer was deleted due to the fact that it returned the count of records instead of just 1
. This can be fixed using the sign
function, leading to this more compact solution:
SELECT sign(count(*)) FROM table WHERE column2 = 4
I posted this because I find it and interesting approach. In production I'd usually end up with something close to RedFilter's answer.