【问题标题】:SQL count all distinct and sub totalsSQL 计算所有不同的总计和小计
【发布时间】:2021-11-11 08:43:09
【问题描述】:

您好,我有一个具有以下架构的表

ID companyID scopeID
1 1 2
2 2 1
3 3 2
4 3 1
5 4 1
6 4 1

我希望能够计算公司的总数,但也能够计算每个范围内有多少公司具有不同的特征。

以表格为例,结果如下:

scopeID Total_disctinct_companies_of_each_scope Total_companies
1 3 4
2 2 4

这意味着每个范围都应该以不同的 companyID 计算,但同​​时我希望能够计算独立于范围的公司总数。

我一直在尝试使用 over() 和 partition by,但由于我没有太多经验,所以我真的不知道该怎么做。

我正在使用 MariaDB。

非常感谢!!

【问题讨论】:

  • 为什么scopeID有4个Total_companies?我只看到 companyID 1 和 3。
  • 在表格中您可以看到公司ID(1、2、3 和4)。它就像一个 count(distinct(companyID)) 而不考虑范围。在同一个查询中做这两件事会导致我遇到麻烦并且不知道该怎么做。
  • 我明白了,我以为是每个 scopeID。

标签: sql count mariadb distinct


【解决方案1】:

您可以单独计算不同公司的总数,然后将其加入到返回每个范围总数的查询中。

select 
    scopeID,
    count(distinct companyID) total_distinct_companies_of_each_scope,
    total.total_companies
from 
    tmp
join 
    (select count(distinct companyID) total_companies from tmp) total
group by scopeID

返回

scopeID total_distinct_companies_of_each_scope total_companies
1 3 4
2 2 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多