假设我在Oracle中有以下表格:
Member Code Cond
1 A Good
1 B Bad
2 B Bad
3 A Good
3 B Good
3 B Bad
如何得到以下结果:
Code Condition Code_Count Uniq_Member_Count
A Good 2 2
B Bad 3 3
B Good 1 0 (Reason why we're setting this 0 because for code B we already counted the unique member on the previous line)
我只是想在一个查询中计算总的uniq成员数,而不考虑条件。希望我的问题有道理。谢谢!
答案 0 :(得分:0)
尝试:
SELECT Code, Cond,
count( code ) as code_count,
count( unique case when cond = mm then member end ) As Uniq_Member_Count
FROM (
SELECT t.*,
min( cond ) Over (Partition by Member, Code ) As mm
FROM table1 t
)
GROUP BY Code, Cond
Order by 1,2
演示:http://sqlfiddle.com/#!4/bc772/14
一个函数:min( cond ) Over (Partition by Member, Code ) As mm
确定一个给定成员被计入的条件cond
,如果该成员属于多个条件。
例如,如果给定成员属于条件A,B,C,那么它将包含在A条件(最小)的计数中,但不包括在B,C中。
在此示例中,成员3属于Bad
和Good
条件,因此它包含在Bad
计数中,因为Bad
< Good
,因此最低为Bad
我不确定我的解释是否明确,抱歉可能会造成混淆。