简体   繁体   English

如何使用两个不同的表获得具有行数的附加列?

[英]How to get additional column with row count using two different tables?

In my database I have usergroup, usergroup_user tables.在我的数据库中,我有 usergroup、usergroup_user 表。 I want to make a SQL query which can result something like result(group_id, name, date, users_count).我想进行一个 SQL 查询,它可能会产生类似 result(group_id, name, date, users_count) 的结果。

usergroup table用户组表

------------------
| group_id| name | 
------------------
|  10     |test1 |
|  11     |test2 |
|  12     |test3 | 
------------------

usergroup_user table usergroup_user 表

---------------------
|group_id | user_id | 
---------------------
|  10     |  100    |
|  10     |  200    |
|  10     |  250    | 
|  11     |  250    | 
|  11     |  700    | 
---------------------

I want to get this kind of a reusult我想得到这样的结果

------------------------------
|group_id | name |users_count| 
------------------------------
|  10     |test1 |  3        | 
|  11     |test2 |  2        |  
|  12     |test3 |  0        | 
------------------------------

You simply do this with the group by, as per the following bellow.您只需按照以下内容对 group by 执行此操作。

SELECT U.group_id ,U.RoleName,COUNT(R.Id)USERCOUNT 
FROM usergroup U
LEFT OUTER JOIN usergroup_user R ON R.group_id =U.group_id 
GROUP BY  U.group_id ,U.RoleName

select group_id, name, (select count(user_id) from [dbo].[usergroup_user] where usergroup_user.group_id=[usergroup].group_id ) AS users_count from [dbo].[usergroup]

SELECT usergroup.group_id ,usergroup.name,COUNT(usergroup_user.id) as users_count 
FROM usergroup 
LEFT OUTER JOIN usergroup_user  ON usergroup.group_id =usergroup_user.group_id 
GROUP BY  usergroup.group_id ,usergroup.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何合并来自不同表的两个“计数”值(2列,非并集) - how to combine two 'count' value from different tables (2 column, NOT union) 如何从两个相关但不同的表中获得不同的用户数 - how to get a Distinct Count of users from two related but different tables 得到两个不同的表中的两个列的区别? - Get the difference of two column in two different tables? SQL 过滤行/如果两个表之间的列中存在数据,则获取行数 - SQL filter row / Get count of rows if data present in column between two tables 如何获取行数作为列 - How to get row count as column 改进查询单个行中两个不同表中的记录数的查询 - Improve a query for the count of records in two different tables in a single row 如何在firebird的两个不同表中获得两个不同的总数? (使用左外部联接联接3个表) - How to get two different total in two different tables in firebird? (Joining 3 Tables using left outer join) 如何从两个表中获取计数结果 - How to get result for count from two tables 如何连接两个表中列名相同但行值不同的两个 SELECT 查询 - How to Join two SELECT queries having same column names but different row values in both tables 合并两个表并添加其他列 - merging two tables and adding additional column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM