从一辆编组由唯一值的另一列

问题描述:

我有一个大表,两列检索所有重复值的计数:从一辆编组由唯一值的另一列

Bld_id - 其中有多个唯一个公寓,因此Bld_id可以重复多次,这取决于在它的公寓数量。

第二列是Appartment_Status它有四个可能的值:

  • ACTIVE,
  • 不活跃
  • NULL
  • (空白)。

所以我希望有我的输出看起来像6列

Bld_id (unique) 
Count(ACTIVE Status) 
Count(NOT ACTIVE Status) 
COUNT (NULL Status) 
Count (blank Satus) 
Count (Total statuses) 

所有独特Bld_id分组表。

这也将是有益的以计数的名称(无状态)

Count (NULL Status) 
Count (blank Satus) 

由于显示,在短短一列下面的两种状态的结果,

让我们尝试一下本作的乐趣

with 
-- 
-- Test case supplied 
-- 
test(Building, Appartement, Status) as 
(
    select 1, 1, 'ACTIVE' from dual union all 
    select 1, 2, 'ACTIVE' from dual union all 
    select 1, 3, 'NOT ACTIVE' from dual union all 
    select 1, 4, 'BLANK' from dual union all 
    select 1, 5, NULL from dual union all 
    select 2, 1, 'ACTIVE' from dual union all 
    select 2, 2, 'BLANK' from dual union all 
    select 2, 3, 'NOT ACTIVE' from dual union all 
    select 2, 4, 'BLANK' from dual union all 
    select 2, 5, NULL from dual 
) 
-- 
-- SELECT statement 
-- 
select Building, 
     sum(case when Status = 'ACTIVE' then 1 else 0 end) active, 
     sum(case when Status = 'NOT ACTIVE' then 1 else 0 end) NOT_active, 
     sum(case when Status = 'BLANK' then 1 else 0 end) Blanks, 
     sum(case when Status is null then 1 else 0 end) IS_NULLS, 
     sum(case when Status is null or status = 'BLANK' then 1 else 0 end) no_status 
    from test 
group by building; 

结果:

BUILDING  ACTIVE NOT_ACTIVE  BLANKS IS_NULLS NO_STATUS 
---------- ---------- ---------- ---------- ---------- ---------- 
    1  2   1  1  1  2 
    2  1   1  2  1  3 

这是你在找什么?

+0

非常感谢。我会尽快尝试。非常多,还有一件事是我想将空白和空值视为一个组合列中的一件事 – enigma6205

+0

根据需要调整查询,但所有逻辑都在那里执行所需操作。玩的开心。 –