sql - 按组和总计数提取计数

标签 sql sql-server count

我有一个第一个选择:

select count(id) from table_user group by idProfile

第二个选择

select count(id) from table_user

如何加入两个选择?

因为至少我需要知道有个人资料的用户部分。

例如:

<表类=“s-表”> <标题> id id配置文件 <正文> 0 1 1 2 2 1 3 3 4 1 5 2 6 2 7 1

预期结果:

<表类=“s-表”> <标题> nbProfileByIdProfile nbTotalProfile IdProfile <正文> 4 8 1 3 8 2 1 8 3

最佳答案

对当前查询的结果进行求和:

select nbProfileByIdProfile, sum(nbProfileByIdProfile) over (), IdProfile
from (
  select count(id) nbProfileByIdProfile, IdProfile
  from table_user
  group by idProfile
) dt

或者,按照 @lemon 的建议 - sum 内的嵌套 count(id):

select count(id) nbProfileByIdProfile, sum(count(id)) over (), IdProfile
from table_user
group by idProfile

演示:https://dbfiddle.uk/uZeeMwHf

关于sql - 按组和总计数提取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77067019/

相关文章:

java - 列数 (1) 与引用键中的列数 (2) 不匹配

c# - 在 Entity Framework 中调用存储过程时的字符串准备

sql-server - 为SQL Server数据库生成数据字典

sql-server - @@DEF_SORTORDER_ID 有何用途?

MySQL:如何查询列并在同一个表中包含来自相关列的信息?

sql - 使用 SQL 生成日期范围

java - 使用 JDBC 连接到 .NET/IKVM 中的 SQL Server

sql - 在 MS Sql Server 中重命名 SQL Server 索引

php - 需要在该文件中添加 count(*) 和 if 语句

mysql - 在 mySQL 的新字段中获取 ROLL UP 或 Count() 总和