Skip to content
Advertisement

Postgresql reference a variable within statement

I come across this scenario frequently in sql and I have seen it done, but would like to summarize the case when/when not to reference a new variable within a statement.

  1. This doesn’t work –
SELECT 
COUNT(id) AS total_id,
COUNT(DISTINCT id) AS distinct_id,
total_id - distinct_id AS var
FROM mytable
  1. but this does –
SELECT 
COUNT(id) AS total_id,
COUNT(DISTINCT id) AS distinct_id,
COUNT(id) - COUNT(DISTINCT id) AS var
FROM mytable

How can I implement scenario 1?

Advertisement

Answer

You can use a subquery.

PostgreSQL:
SELECT total_id, distinct_id, (total_id + distinct_id) as var FROM
(
    SELECT COUNT(id) AS total_id, COUNT(DISTINCT id) AS distinct_id
    FROM mytable
) as m
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement