使用SQL Query连接两个表时计算右表的行数

时间:2013-02-20 03:41:47

标签: sql

我对SQL查询有疑问。让我举个例子说明我的问题: 我有两个这样的表:

角色表

ID                    Role                        Role Description
1                     Administrator               Someone in administrator board
2                     User                        Someone who has an account
3                     Guess                       Someone who just view the website

用户表

ID                  Username                 RoleID
1                    trind08                      1
2                    trind09                      1
3                    trind10                      1
4                    kimchi                       2
5                    linhchi                      2
6                    thanh01                      2
7                    thanh02                      3
8                    kiemanh                      3
9                    liemanh                      3

我的问题是我想查看所有角色并计算解决这些角色的用户。

运行查询后,

结果表可能如下所示:

ID                Role                            Role Description                                Cound of User
1                 Administrator                   Someone in administrator board                  3
2                 User                            Someone who has an account                      3
3                 Guess                           Someone who just view the website               3

我第一次尝试创建这样的SQL查询:

select rol.*, usrCout as 'Count of User' from Roles rol
left join (select count(*) from Users where RoleID == rol.ID) usrCout;

但我的查询运行失败,我无法得到我想要的结果。请帮助我。

谢谢

2 个答案:

答案 0 :(得分:2)

SELECT 
ID
,ROLE
,Role Description
,(SELECT COUNT(*) FROM Users where RoleID = rol.ID) AS UserCount
FROM Roles rol

答案 1 :(得分:1)

尝试此查询

Select count(*) as 'Count of User', r.RoleID, Role, Role Description from role r, Users u where u.RoleId = r.Id group by r.RoleID,Role, Role Description;

Fiddle

希望这有帮助