如何限制 sql-server (2005) 中 GROUP BY 子句的答案

发布于 2024-10-20 22:55:51 字数 437 浏览 1 评论 0原文

我正在尝试获取数据库中所有客户列表的前 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好听的两个字的网名 2024-10-27 22:55:51
;WITH cte
     As (SELECT clientid,
                city,
                COUNT(city) as cnt,
                ROW_NUMBER() OVER (PARTITION BY clientid 
                                       ORDER BY COUNT(city)) AS RN
         FROM   customers
         GROUP  BY clientid,
                   city)
SELECT clientid,
       city
FROM   cte
WHERE  RN <= 50  
;WITH cte
     As (SELECT clientid,
                city,
                COUNT(city) as cnt,
                ROW_NUMBER() OVER (PARTITION BY clientid 
                                       ORDER BY COUNT(city)) AS RN
         FROM   customers
         GROUP  BY clientid,
                   city)
SELECT clientid,
       city
FROM   cte
WHERE  RN <= 50  
待"谢繁草 2024-10-27 22:55:51

我认为这可能会做到这一点:

select top 50 city
from (select city from customers group by city order by count(clientid) desc)

我假设如果 clientID 与城市位于同一行,那么该 clientID 代表居住在该城市的用户。

I think this might do it:

select top 50 city
from (select city from customers group by city order by count(clientid) desc)

I assume if a clientID is in the same row as a city, then that clientID represents a user living in that city.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文