I'm trying write a Postgres query to display a distinct number of people but count the actual (non-distinct) number of people.
So if I have
1 Ray ray@gmail.com
2 Ray ray@gmail.com
3 Kate kate@gmail.com
I'd want to show:
Ray 2
Kate 1
==
SELECT name, email, COUNT(*)
FROM (SELECT DISTINCT name, email
FROM people
WHERE degree = 'Gradiate')
I get:
ERROR: subquery in FROM must have an alias
LINE 3: FROM (SELECT DISTINCT name, email
How to fix this?
You do not need the subquery at all (which would require a table alias as has been pointed out). It wouldn't make sense for what you need.
Use GROUP BY
like this:
SELECT name, email, count(*) AS ct
FROM people
WHERE degree = 'Graduate'
GROUP BY 1, 2;
GROUP BY 1, 2
is shorthand for GROUP BY name, email
in this case. Example with more details.
Of course, name
and email
have to match here, unlike your example where you only display name
and count (which contradicts your query).
Add an
AS some_alias
Like:
SELECT name, email, COUNT(*)
FROM (SELECT DISTINCT name, email
FROM people
WHERE degree = 'Gradiate') as my_alias
SELECT name, count(*) AS count
FROM people
WHERE degree = 'Gradiate'
GROUP BY name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.