2017-05-24 64 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 
相关问题