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.
- This doesn’t work –
SELECT COUNT(id) AS total_id, COUNT(DISTINCT id) AS distinct_id, total_id - distinct_id AS var FROM mytable
- 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