簡體   English   中英

SQL如何在另一列不同時計算一列

[英]SQL How to count one column when another column is distinct

我有一張桌子,看起來像這樣:

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

當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;

如果您使用的是MySQL,那么您可以編寫如下內容:

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

我在這里假設,添加一些預期結果,但:

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

將為您提供final_aid_status列中每個值的student_number列中不同值的計數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM