在其他表中创建总价值计数的提示

时间:2019-04-24 19:58:08

标签: sql oracle

我有多个表,每个表中都有一个状态列。我想显示每个表每个状态的计数摘要。像这样:

=============================================

Status   |  Table A  |  Table B  |  Table C  |

Status A |   3     |     8     |    2      |

Status B |     5     |     7     |    4      |

==============================================

我不确定该如何解决此问题,因此需要入门帮助。我可以执行简单的COUNT函数,例如:

SELECT status, count(status) from TABLE_A group by status

但是我不确定如何以所需的形式填充数据,或者在可能的情况下如何将表名用作列标题。我希望方向正确。谢谢!

3 个答案:

答案 0 :(得分:0)

可能正在使用左联接

 select t.status, a.cnt A, b.cnt B,c.cnt C
from( 
  select  status 
  from  tableA 
  union 
  select  status 
  from  tableB
  select  status 
  from  tableC

  ) t 
  left join (
      select status, count(*) cnt
      from  tableA
      group by status 
  ) a ON  on t.status  = a.status 

  left join (
      select status, count(*) cnt
      from  tableB
      group by status 
  ) b ON  on t.status  = b.status 
  left join (
      select status, count(*) cnt
      from  tableC
      group by status 
  ) c ON  on t.status  = c.status 

答案 1 :(得分:0)

在分别计算每个表的计数后,可以尝试进行左联接。

select distinct t1.status, 
  count(t1.status) as [tableA], 
   t2.TableB, 
   t3.TableC from Table A t1
left join (
         select distinct status, 
         count(status) as [TableB] from Table B 
         group by status
) t2 on t1.status=t2.status
left join (
         select distinct status, 
         count(status) as [TableC] from Table C 
         group by status
) t3 on t1.status=t3.status
group by t1.Status 

答案 2 :(得分:0)

我将使用union all和聚合:

select status, sum(a) as a, sum(b) as b, sum(c) as c
from ((select status, count(*) as a, 0 as b, 0 as c
       from tablea
       group by status
      ) union all
      (select status, 0, count(*), 0 
       from tableb
       group by status
      ) union all
      (select status, 0, 0, count(*)
       from tablea
       group by status
      )
     ) abc
group by status;

即使在一个或多个表缺少某些status值的情况下,这也可以确保显示所有行。