【问题标题】:SQL How to count one column when another column is distinctSQL如何在另一列不同时计算一列
【发布时间】:2018-03-07 19:31:44
【问题描述】:

我有一个看起来像这样的表:

fin_aid_status | student_number
---------------|---------------
YES            | 111222
YES            | 111222
               | 111333
YES            | 111444

我想计算 fin_aid_status 的数量,但不是重复计算 student_number 重复的行数。所以我想从这个表中得到的结果是 2。不是 3,因为111222 在表中出现了两次。表中还有许多其他列,因此仅在表中查找唯一值是行不通的。

编辑:这是Oracle

例如,我已经在使用这样的代码:

select count(*), count(distinct student_number) from table

所以对于第三列,我想用唯一的学生编号来计算经济援助的数量。

所以我的预期输出是:

count(*) | count(distinct student_number) | count_fin_aid
4        | 3                              | 2

【问题讨论】:

  • 请。标记您正在使用的数据库名称(mysql、mssql、orcle 等)
  • 还添加您的预期结果,您尝试过的代码。
  • 我编辑了我原来的问题。

标签: sql oracle count duplicates


【解决方案1】:

当 fin_aid_status 不为 null 时,使用 case 语句评估 student_number;然后计算不同的值。

SELECT count(Distinct case when fin_aid_status is not null 
                           then student_number end)  as Distinct_Student
FROM tbl;

使用样本数据的结果:2

给定甲骨文:

With cte (fin_aid_status, student_number) as (
SELECT 'YES'            , 111222 from dual union all
SELECT 'YES'            , 111222 from dual union all
SELECT ''               , 111333 from dual union all
SELECT 'YES'            , 111444 from dual )
SELECT count(Distinct case when fin_aid_status is not null 
                           then student_number end) as DistinctStudentCnt 
FROM  cte;

【讨论】:

    【解决方案2】:

    如果你使用 MySQL,你可以写如下,如果你想要的只是计数

    SELECT count(DISTINCT student_number) FROM your_table WHERE fin_aid_status = 'YES';
    

    【讨论】:

    • 我不能这样做,因为那样我正在做的其他计数会因为 fin_aid_status 而被毁掉。
    【解决方案3】:

    我在这里假设,添加一些预期的结果但是:

    SELECT fin_aid_status,
           COUNT(DISTINCT student_number)
    FROM tablename
    GROUP BY fin_aid_status;
    

    将为您提供 fin_aid_status 列中每个值的 student_number 列中不同值的计数

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多