1

Below is the different scales in a POS system. I am trying to count the number of distinct scales that are not 'MANUAL WT'.

This is what I have, but it is returning 2 and not 6. count (distinct (case when d.SCALE_IN_ID != 'MANUAL WT' then 1 else 0 end)) as Num_Scale

enter image description here

GMB
  • 216,147
  • 25
  • 84
  • 135
sqlnoob
  • 19
  • 3

3 Answers3

3

Consider:

select count(distinct case when scale_in_id <> 'MANUAL WT' then scale_in_id end) cnt
from mytable

The problem with your original query is that the case expression turns values to either 0 and 1, and then the aggregate function computes how many distinct values are returned: since values are all 0s or 1s, there are only two distinct values (or one in edge cases): hence the result that you are getting.

GMB
  • 216,147
  • 25
  • 84
  • 135
1

A simple WHERE clause will do:

select count(distinct scale_in_id) Num_Scale
from tablename
where scale_in_id <> 'MANUAL WT'
forpas
  • 160,666
  • 10
  • 38
  • 76
0

The value that you want to exclude may be replaced by NULL. Count excludes NULL:

select count(distinct case when scale_in_id <> 'MANUAL WT' then scale_in_id else NULL end) cnt
from mytable
Adriaan
  • 17,741
  • 7
  • 42
  • 75