2017-01-26 76 views
0

在Oracle SQL我有一个表,最后,像这样的:的Oracle SQL一列数的情况下

-------------------- 
-- ID  -- TYPE 
-------------------- 
-- 123  -- A 
-- 123  -- A 
-- 123  -- B 
-- 123  -- B 
-- 123  -- C 
-- 124  -- B 
-- 124  -- B 
-- 124  -- C 
-- ...  -- ... 

,我希望像这样的输出:

---------------------------------------------------------------------------------- 
-- Count distinct IDs -- count (type A) -- count (type B) -- count (type C) 
-- 10000    -- 5000   -- 4000   -- 1000 
---------------------------------------------------------------------------------- 

我的一部分遇到麻烦的是,一旦一个ID被计入A型,它就不能是B或C.一旦它被计入B型,它就不能成为C并且不可能成为A.要成为C,它必须被计入A或B.

到目前为止,我有类似

select 
count(distinct FINAL.ID) 
from 
FINAL 

A,B和C是唯一可能的值。

+0

A,B和C是唯一可能的值吗?如果还有其他值可能,你只需要计算A,B和C? (如果**这两个**问题的答案都是**否**,那么没有动态SQL,您可能无法实现所需内容)。 – mathguy

+0

A,B和C是唯一可能的值。 –

回答

1

像这样可能工作:

select count(*) as ct_id, 
     count(case type when 'A' then 1 end) as ct_a, 
     count(case type when 'B' then 1 end) as ct_b, 
     count(case type when 'C' then 1 end) as ct_c 
from (
     select id, min(type) as type 
     from  final 
     group by id 
    ) 
; 

子查询采用的“明显的”治疗(因为它产生为每个不同的id单个行),它只是选择每个id“最小” type 。外部查询执行总计数和条件计数。

+0

它的工作原理!非常感谢数学! –