sql中如何计算计数?
我有下表:
memberid
2
2
3
4
3
...我想要以下结果:
memberid count
2 2
3 1 ---Edit by gbn: do you mean 2?
4 1
我试图使用:
SELECT MemberID,
COUNT(MemberID)
FROM YourTable
GROUP BY MemberID
...但现在我想找到哪个记录具有最大计数。 IE:
memberid count
2 2
I have the following table:
memberid
2
2
3
4
3
...and I want the following result:
memberid count
2 2
3 1 ---Edit by gbn: do you mean 2?
4 1
I was attempting to use:
SELECT MemberID,
COUNT(MemberID)
FROM YourTable
GROUP BY MemberID
...but now I want find which record which has maximum count. IE:
memberid count
2 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这应该可以实现不需要子选择的技巧:
This should do the trick with no subselects required:
可以很容易地完成:
Can be done quite easy:
我相信原始发帖者要求 2 个结果集。
我知道获得此信息的唯一方法(在 SQL Server 中)是将原始记录转储到临时表中,然后对其执行 SELECT 和 MAX。我确实欢迎需要更少代码的答案!
I believe the original poster requested 2 result sets.
The only way I know of to get this (in SQL Server) is to dump the original records into a temp table and then do a SELECT and MAX on that. I do welcome an answer that requires less code!
这个查询怎么样:
How about this query:
选择计数(列名)
来自你的表;
SELECT count(column_name)
FROM your_table;
您需要使用子选择:
需要第二个分组依据来返回计数和 MemberID。
You need to use a subselect:
The second group by is needed to return both, the count and the MemberID.
尽管如此,它不会满足您想要的输出,因为您有两次“memberid = 3”。
编辑:在问题更新后...
Although, it won't work for your desired output because you have "memberid = 3" twice.
Edit: After late update to question...
如果最大值并列(或更多)怎么办?您想显示其中一项还是全部?
这就是我要做的事情,
但我希望看到一种更有效的方法。
What if there is a tie (or more) for the max? Do you want to display one or all?
This is how I would do this
I would love to see a more efficient approach though.
这样做:
Do it like this: