2017-05-24 104 views
0

的不同組合的計數:Teradata的:返回我有一個看起來像這樣的數據集列

SocialSecurityNumber | ProgramEnrollmentStatus | Contact_Preference | 
--------------------------------------------------------------------- 
920421     Enrolled    Daytime 
870725     Not Enrolled   Night 
630126     Undecided    Night 
630126     Undecided    Night 
920421     Enrolled    Daytime 
910510     Undecided    Anytime 
921115     Enrolled    Night 
921115     Enrolled    Night 
910510     Undecided    Anytime 
950202     Enrolled    Daytime 

利用這些數據,我想編寫一個返回這樣數據的代碼:

Contact_Preference | ProgramEnrollmentStatus | Count_Unique_SSN 
Night    Enrolled      1 
Night    Undecided      1 
Night    Not Enrolled     1 
Anytime    Enrolled      0 
Anytime    Undecided      1 
Anytime    Not Enrolled     0 
Daytime    Enrolled      2 
Daytime    Undecided      0 
Daytime    Not Enrolled     0 
+1

什麼是從寫代碼阻止你?你可以發佈你當前的查詢,爲什麼它不能正常工作。 –

回答

1

這很棘手,因爲您必須生成具有零值的行。爲此,請使用cross join。剩下的就是left joingroup by

select cp.contact_preference, pes.ProgramEnrollmentStatus, 
     count(distinct SocialSecurityNumber) 
from (select distinct contact_preference from t) cp cross join 
    (select distinct ProgramEnrollmentStatus from t) pes left join 
    t 
    on t.contact_preference = cp.contact_preference and 
     t.ProgramEnrollmentStatus = pes.ProgramEnrollmentStatus 
group by cp.contact_preference, pes.ProgramEnrollmentStatus 
相關問題