0

I would like to count the number of observations in a where clause, and then divide that result by the result of a count with a different where clause. Is that possible in a single query? Both operations are on the same table.

I've tried this so far:

SELECT 
  filter(COUNT(DISTINCT table.column1) WHERE table.column2 <> 'var_1') / 
  filter(COUNT(DISTINCT table.column1) WHERE table.column2 == 'var_2')
FROM table

and

SELECT result1 / COUNT(DISTINCT table.column1) AS result2
FROM
(
SELECT COUNT(DISTINCT table.column1) AS result1
FROM table
WHERE table.column2 <> 'var_1'
) AS inner_query
WHERE table.column2 <> 'var_2'

With very little success. Any suggestions?

lemon
  • 14,875
  • 6
  • 18
  • 38
James
  • 463
  • 4
  • 13

1 Answers1

1

In many SQL engine, you can do something like below. Define the numerator and the denominator in separate tables and join together.

SELECT
  a.result1 / b.result2
FROM
  ( SELECT COUNT(DISTINCT column1) AS result1 
    FROM table
    WHERE table.column2 <> 'var_1' ) AS a,
  ( SELECT COUNT(DISTINCT column1) AS result2
    FROM table
    WHERE table.column2 == 'var_2' ) AS b
Kota Mori
  • 6,510
  • 1
  • 21
  • 25