如何使用分析计数来有条件地计数?

时间:2014-06-12 22:54:32

标签: sql oracle11g analytics

使用这个例子,我如何调整我的sql来报告listing_id是否通过了所有测试?

with listing_row 
as
(
select 1 as listing_id, 'TEST1' as listing_test, 'Y' as pass_yn from dual union all  
select 1 as listing_id, 'TEST2' as listing_test, 'Y' as pass_yn from dual union all
select 1 as listing_id, 'TEST3' as listing_test, 'Y' as pass_yn from dual union all

select 2 as listing_id, 'TEST1' as listing_test, 'N' as pass_yn from dual union all  
select 2 as listing_id, 'TEST2' as listing_test, 'Y' as pass_yn from dual union all
select 2 as listing_id, 'TEST3' as listing_test, 'N' as pass_yn from dual union all

select 3 as listing_id, 'TEST1' as listing_test, 'N' as pass_yn from dual union all  
select 3 as listing_id, 'TEST2' as listing_test, 'N' as pass_yn from dual union all
select 3 as listing_id, 'TEST3' as listing_test, 'N' as pass_yn from dual)
select listing_id, 
       listing_test,pass_yn, 
       count(*) over (partition by listing_id, pass_yn) as all_y,
       count(*) over (partition by listing_id, pass_yn) as all_n
         from listing_row

期望的结果

LISTING_ID   ALL_Y ALL_N
1            Y       N
2            N       N
3            N       Y    

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用min()max()

select listing_id, 
       listing_test, pass_yn, 
       min(pass_yn) over (partition by listing_id) as all_y,
       min(case when pass_yn = 'Y' then 'N' else 'Y' end) over (partition by listing_id) as all_n
from listing_row;

这使用基于“Y”>事实的技巧。 “N”。因此,如果您使用列的min()并且它具有任何“N”值,则结果将为“N”。

答案 1 :(得分:1)

这是使用sum()的另一种解决方案:

SELECT listing_id,
       CASE WHEN max(all_test_cnt)-MAX(num_of_test) = 0 THEN 'Y' ELSE 'N' END all_y,
       CASE WHEN MAX(num_of_test) = 0 THEN 'Y' ELSE 'N' END all_n
FROM
    (SELECT listing_id,
           COUNT(DISTINCT listing_test) OVER (PARTITION BY NULL) all_test_cnt,
           SUM(CASE WHEN pass_yn = 'Y' THEN 1 ELSE 0 END) OVER (PARTITION BY listing_id)num_of_test
    FROM listing_row)

GROUP BY listing_id