如何限制 sql-server (2005) 中 GROUP BY 子句的答案
我正在尝试获取数据库中所有客户列表的前 50 个城市 (如此简化:每个客户都有一个具有关联数据的客户列表(例如城市))
如果我说:
SELECT top(50) clientid, city, COUNT(city) as cnt
FROM customers
GROUP BY clientid, city
ORDER by cnt
它将把总结果集限制在 50 行,而不是限制每个组的结果。
如何获取每个 clientid 的前 50 名?
编辑: 我搜索了 stackoverflow(并用 google 搜索),但只找到了 Mysql 的解决方案。可能搜索“limit”只会找到 mysql 解决方案 wince 这是该数据库引擎所需的关键字。如果我知道 Sql-Server 中所需的关键字,我也可以使用 google 找到它。
I'm trying to get the top 50 cities for all customer lists in our DB
(So simplified: every client has a list of customers with associated data(like the city))
If I say:
SELECT top(50) clientid, city, COUNT(city) as cnt
FROM customers
GROUP BY clientid, city
ORDER by cnt
it will limit the total resultset on 50 rows instead of limiting the results for every group.
How can I get the top 50 per clientid?
EDIT:
I searched stackoverflow (and googled) but only found solutions for Mysql. Probably searching for 'limit' will only find mysql solutions wince thats the keyword needed for that Database engine. If I know the keyword needed in Sql-Server I could find it as well using google.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这可能会做到这一点:
我假设如果 clientID 与城市位于同一行,那么该 clientID 代表居住在该城市的用户。
I think this might do it:
I assume if a clientID is in the same row as a city, then that clientID represents a user living in that city.