2017-09-26 25 views
0

我有一個表,看起來是這樣的:SQL如何算一列時,另一列是不同的

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

我要計算其中student_number被複制fin_aid_status但不重複計算的行數。所以我想從這張表中得到的結果是2.不是3,因爲111222在表格中兩次。表格中還有許多其他列,但只是在表格中尋找唯一值將不起作用。

編輯:這是甲骨文

比如我使用這樣的代碼已經:

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

因此,對於第三列我會想依靠獨特的學生人數財政援助的數量。

所以我期望的輸出將是:

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

PLS。標記您正在使用的數據庫名稱(mysql,mssql,orcle等) –

+0

也會添加您的預期結果,您嘗試過的代碼。 –

+0

我編輯了我原來的問題。 –

回答

1

當fin_aid_status不爲空時,使用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; 
+0

是的!!!非常感謝!這正是我需要的。 –

0

如果你正在使用MySQL,你可以如下寫的東西,如果你想要的是數

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

我不能這樣做,因爲那麼我做的其他計數將會因爲fin_aid_status而被破壞。 –

0

我假設在這裏,加一些預期的結果,但:

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

會給你每個v的student_number列中不同值的計數在fin_aid_status列中的線索

相關問題