0

I need to do some simple calculations counting the percentage ranges of each project. It seems as if this should be a very simple straightforward query but my results (counts of percentages <10%, >50%, and >100% are coming back incorrect and I'm having trouble figuring out why. I'm working in db2 and here is a sample of my data.

enter image description here

My query that returns the incorrect results ("24") is:

SELECT 
                COUNT(*)
            FROM Fact_Table
            WHERE Dept_NAME = 'sales'
                AND PERCENTAGE_USED > '100.00%'
4

4 回答 4

1

I'm not too sure what you are expecting or what the field data types are set as, but could this be down to you comparing a string value rather than a numeric one for the comparison > '100.00%'

于 2013-09-10T13:38:39.730 回答
1

It's probably because you are comparing strings instead of numbers. The string '2%' is "greater" than, that is, sorted after the string '100%'. If you really are storing percentages as strings in your fact table, which is not very wise, you'll need to convert them to numbers before the comparison.

于 2013-09-10T13:40:04.487 回答
1

It looks like your values are being stored as strings (hence the '%') rather than as numbers.

Here is a method to compare them as numbers, and do the ranges at the same time:

SELECT (case when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 10 then '<10'
             when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 50 then '10-50'
             when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 100 then '50-100'
             when cast(replace(PERCENTAGE_USED, '%', '') as float) > 100 then '>100'
        end) as range,
       COUNT(*)
WHERE Dept_NAME = 'sales'
GROUP BY (case when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 10 then '<10'
               when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 50 then '10-50'
               when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 100 then '50-100'
               when cast(replace(PERCENTAGE_USED, '%', '') as float) > 100 then '>100'
          end);
于 2013-09-10T13:42:42.150 回答
0

The where clause of your query is comparing the strings. You want to compare the numbers.

于 2013-09-10T13:39:24.923 回答