如何在 Sql Server 的 SELECT CASE 子句的比较中使用 COUNT()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13140545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:51:16  来源:igfitidea点击:

How can you use COUNT() in a comparison in a SELECT CASE clause in Sql Server?

sqlsql-servercountaggregate-functionsselect-case

提问by Panzercrisis

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!

基本上只在表中有一行或多行时返回 1,否则返回 0。必须有一种语法正确的方法来做到这一点。可能是什么?谢谢!

采纳答案by tempidope

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

参考:http: //msdn.microsoft.com/en-us/library/ms181765.aspx

回答by RedFilter

Question: return 1 when there's one or more rows in the table, 0 otherwise:

问题:当表中有一行或多行时返回 1,否则返回 0

In this case, there is no need for COUNT. Instead, use EXISTS, which rather than counting all records will return as soon as anyis found, which performs much better:

在这种情况下,不需要COUNT. 相反,使用 use EXISTS,而不是计算所有记录,一旦找到任何记录就会返回,它的性能要好得多:

SELECT CASE 
    WHEN EXISTS (SELECT 1 FROM table WHERE column2 = 4)    
        THEN 1  
    ELSE 0 
END

回答by Cristian Lupascu

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 signfunction, leading to this more compact solution:

Mahmoud Gammal 以一种有趣的方式发布了一个答案。不幸的是,答案被删除了,因为它返回的是记录数而不是1. 这可以使用固定sign功能,导致这种更紧凑的解决方案:

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.

我发布这个是因为我发现它和有趣的方法。在生产中,我通常会得到接近 RedFilter 答案的结果。