0

I'm trying to add count statements in SQL that have conditions, and I keep getting an error. Below is my code:

  SELECT 
  (100.0*(COUNT(CASE [TYPE] WHEN 500 THEN 1 ELSE NULL END)) / (100*
  (COUNT(CASE [TYPE] WHEN 400 THEN 1 ELSE NULL END + COUNT(CASE [TYPE] WHEN 
  300 THEN 1 ELSE NULL END))) AS Ratio
  FROM historytable

Basically I'm trying to get the percentage of count of activity type 500 divided by count of activity type 400 and 300, and I keep getting an error.

2
  • 1
    What's the error? What RDBMS are you using? Commented Jun 21, 2017 at 18:08
  • Change the NULL to 0. That's probably your issue. Commented Jun 21, 2017 at 18:08

2 Answers 2

3

I would write this as:

 SELECT (sum(case when [type] = 500 then 100.0 else 0 end) /
         sum(case when [type] in (300, 400) then 1 end)
        ) as ratio
 FROM historytable;

I prefer sum() to count() for this type of calculation (personal preference, count() is fine). Your problem is a missing paren in the denominator.

Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this.

SELECT (
  100.0 *(
      SELECT count( * )
      FROM historytable
      WHERE [type]=500
  ) / ( 
    100 * (
      (
        SELECT count( * )
        FROM historytable
        WHERE [type]=400
      ) + (
        SELECT count( * )
        FROM historytable
        WHERE [type]=300
      )
    )
  )
) as ratio

Using a mysql database I was able to test this on a data table with [type] and values specific to that table.

SELECT (
  100.0 *(
      SELECT count(*) FROM my_table WHERE record_type='value_1'
  ) / ( 
      100 *(
          (
              SELECT count(*) FROM my_table WHERE record_type='value_2'
          ) + (
              SELECT count( * ) FROM my_table WHERE record_type='value_3'
          )
      )
  )
) as ratio;
+---------+
| ratio   |
+---------+
| 1.61804 |
+---------+
1 row in

 set (0.00 sec)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.