SQL计数,分组,并从另一个表中检索相关数据

时间:2017-05-25 15:00:32

标签: sql-server

我写了以下问题:

SELECT [User], count(*) as Records 
FROM dbo.PBBuilds 
GROUP BY [User] 
ORDER BY [Records] DESC

它选择一个USERID并计算与记录相关联的一个或多个行。

--------------------------------------------------
| Users                                 | records | 
------------------------------------------------- |
| 0ca3f535-96f2-4926-9b4d-25fb2aa713eb  |    3    |
| a32d1784-d636-4caf-bb9d-60bfbfc1aadf  |    2    |
| 5fabb0aa-f61f-4180-90f6-5dd1650fd0db  |    1    |
---------------------------------------------------

“用户”列与另一个存储用户名的表中的ID列相关。如何通过此链接检索和匹配数据?

1 个答案:

答案 0 :(得分:2)

假设您的另一个表名为other_table,并且在User列中也有ID,则:

SELECT UserName, COUNT(*) Records 
FROM dbo.PBBuilds b INNER JOIN other_table o
on b.User = o.User
GROUP BY UserName
ORDER BY COUNT(*) DESC