我是sql的新手,我认为我需要一些基础知识的帮助。
我想显示前10名用户名和用户朋友的数量。我该怎么做?
前10名将列出最多朋友按降序排列的用户但问题是我不知道如何使用代码执行此操作。
app_id是用户
app_friends_id是用户朋友
app_id app_friends_id
40 20
40 10
30 30
40 50
有3个app_id有40个,所以我想显示app_id 40和app_friends_id的总数3.很抱歉我的解释不错。
答案 0 :(得分:2)
如果我理解,你可以试试这个:
SELECT TOP 10 app_id,COUNT(app_id) as 'count_of_friend'
FROM table
GROUP BY app_id
ORDER BY 2 DESC
结果是:
app_id count_of_friend
40 3
30 1
答案 1 :(得分:1)
我不确定您的数据库是如何设置的,因为朋友表可能有点“怪异”,#34;但你可能想做这样的事情:
SELECT TOP 10 app_id, COUNT(*)
FROM tableName
GROUP BY app_id
ORDER BY COUNT(*) DESC
另一方面,如果你的表被设置为两个列引用可能引用相同的用户没有特定的顺序(我怀疑是这种情况),你可能想要将它与自己联合起来使用CTE。这假设您正在使用SQL Server。在MySQL中,您可以执行具有类似内容的嵌套查询。
; WITH cte AS
(
SELECT TOP 10 app_id AS [user], COUNT(*) AS [count]
FROM tableName
GROUP BY app_id
UNION ALL
SELECT TOP 10 app_friends_id AS [user], COUNT(*) AS [count]
FROM tableName
GROUP BY app_friends_id
)
SELECT TOP 10 [user], SUM([count])
FROM cte
GROUP BY [user]
ORDER BY SUM([count]) DESC