我尝试编写Postgres查询以显示不同数量的人,但计算实际(非独特)人数。
所以,如果我有
1 Ray ray@gmail.com
2 Ray ray@gmail.com
3 Kate kate@gmail.com
我想要展示:
Ray 2
Kate 1
==
SELECT name, email, COUNT(*)
FROM (SELECT DISTINCT name, email
FROM people
WHERE degree = 'Gradiate')
我明白了:
ERROR: subquery in FROM must have an alias
LINE 3: FROM (SELECT DISTINCT name, email
如何解决这个问题?
答案 0 :(得分:2)
你根本不需要子查询(这需要一个已经指出的表别名)。对你需要的东西没有意义。
像这样使用GROUP BY
:
SELECT name, email, count(*) AS ct
FROM people
WHERE degree = 'Graduate'
GROUP BY 1, 2;
在这种情况下, GROUP BY 1, 2
是GROUP BY name, email
的简写。 Example with more details.
当然,name
和 email
必须与此匹配,不像您只展示name
和计数(与您的查询相矛盾)的示例。
答案 1 :(得分:0)
添加
AS some_alias
像:
SELECT name, email, COUNT(*)
FROM (SELECT DISTINCT name, email
FROM people
WHERE degree = 'Gradiate') as my_alias
答案 2 :(得分:0)
SELECT name, count(*) AS count
FROM people
WHERE degree = 'Gradiate'
GROUP BY name;