SQL 检查所有行的列中的值是否正好是值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5449134/
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 09:53:42  来源:igfitidea点击:

Check if value in column for all rows is exactly value

sql

提问by gilhanan

For example, I want follow the number 2 as target

例如,我想按照数字 2 作为目标

This should return positive indication:

这应该返回积极的迹象:

ID       Status
123      2
432      2
531      2
123      2

This should return negative indication:

这应该返回否定指示:

ID       Status
123      1
432      3
531      2
123      2

This should return negative indication:

这应该返回否定指示:

ID       Status
123      1
432      1
531      1
123      1

Thanks

谢谢

回答by Martin Smith

EXISTSshould be used in preference to COUNTso it can return as soon as the first non matching row is found.

EXISTS应该优先使用 toCOUNT以便它可以在找到第一个不匹配的行后立即返回。

SELECT CASE
         WHEN NOT EXISTS(SELECT *
                         FROM   your_table
                         WHERE  status <> 2) THEN 'Y'
         ELSE 'N'
       END AS your_result  

You don't state RDBMS. You might need to append FROM DUALonto the end of the above dependant on flavour.

您没有说明 RDBMS。FROM DUAL根据口味,您可能需要附加到上述内容的末尾。

回答by Tim

select (select count(distinct status) from T)  = 1 

will return 1 or 0 (i.e. true or false) depending on whether all of the rows have the same value in Status or not. If you have to deal with NULL values in status:

将返回 1 或 0(即 true 或 false),具体取决于所有行在 Status 中是否具有相同的值。如果您必须处理状态中的 NULL 值:

select exists 
( select status from T where status <> 2 or status is null)
as StatusContainsOtherThanTwoOrNullValue

回答by RedGrittyBrick

select count(*) where Status != 2

select count(*) where Status != 2