11

For example, I want follow the number 2 as target

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

Dan Atkinson
  • 11,046
  • 14
  • 81
  • 111
gilhanan
  • 285
  • 1
  • 5
  • 16

3 Answers3

17

EXISTS should be used in preference to COUNT so it can return as soon as the first non matching row is found.

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 DUAL onto the end of the above dependant on flavour.

Martin Smith
  • 419,657
  • 83
  • 708
  • 800
4

select count(*) where Status != 2

RedGrittyBrick
  • 3,679
  • 1
  • 26
  • 46
4
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:

select exists 
( select status from T where status <> 2 or status is null)
as StatusContainsOtherThanTwoOrNullValue
Tatranskymedved
  • 3,811
  • 3
  • 21
  • 45
Tim
  • 5,351
  • 3
  • 31
  • 41