Oracle SQL 沿着常规列返回 count(*) 列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11210621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oracle SQL return count(*) column along side of regular column?
提问by Xonatron
In Oracle SQL, how do I return count(*) column along side of a regular column?
在 Oracle SQL 中,如何在常规列的旁边返回 count(*) 列?
What works:
什么工作:
select count(*) from TABLE where username = 'USERNAME';
What I'd like to work:
我想做什么:
select username,count(*) from TABLE where username = 'USERNAME';
So I want the username along side of the count, to expand this into another query that lists numerous usernames and the count of their records.
所以我想要在计数旁边的用户名,将其扩展为另一个查询,列出众多用户名及其记录计数。
Error:
错误:
ORA-00937: not a single-group group function
00937. 00000 - "not a single-group group function"
*Cause:
*Action:
Error at Line: 7 Column: 7
Question:
题:
So, how do I do it?
那么,我该怎么做呢?
回答by Sean Johnson
SELECT username,count(*) from TABLE WHERE username='USERNAME' GROUP BY username
should do the trick!
应该做的伎俩!
The reason the first query works is because MySQL can automatically convert that query into an aggregate query, because it "understands" that you want to count all of the rows where username='USERNAME'. The second query isn't clear enough - you're trying to perform an aggregate function on rows selected by the query, but you also want the rows of the query. My query makes it clear that you only expect one username returned out of the set, so aggregation is not a problem.
第一个查询有效的原因是因为 MySQL 可以自动将该查询转换为聚合查询,因为它“理解”您想要计算 username='USERNAME' 的所有行。第二个查询不够清楚 - 您试图对查询选择的行执行聚合函数,但您还需要查询的行。我的查询清楚地表明您只希望从集合中返回一个用户名,因此聚合不是问题。