创建oracle视图以连接一个或多个表中的值

时间:2014-10-15 03:09:02

标签: sql oracle

首先,我有两张桌子,

TABLEA,

NAME(PK) COMPONENT_TYPE COMP_STATUS
HEAD1    COLUMN         NOTISSUED
HEAD2    COLUMN         ISSUED
HEAD3    COLUMN         NOTISSUED
HEAD4    COLUMN         NOTISSUED
HEAD5    BRACING        ISSUED
HEAD6    BRACING        ISSUED
HEAD7    BRACING        ISSUED
HEAD6    BRACING        NOTISSUED

TABLEB,

NAME   PROCESS_STATUS 
HEAD1  0
HEAD2  100
HEAD3  0
HEAD4  0
HEAD5  100
HEAD6  100
HEAD7  0
HEAD6  0

我想要的结果是,

COMPONENT_RES TOTAL_COMP ISSUED_QTY COMPLETED_PROCESS_QTY
COLUMN        4          1          1
BRACING       4          3          2

因此,我们的想法是创建一个从不同表中进行子操作的视图。

我试过这个

SELECT DISTINCT TABLEA.COMPONENT_TYPE, 
    SELECT SUM(TABLEA.COMPONENT_TYPE), 
    (SELECT SUM(TABLEA.COMP_STATUS) WHERE COMP_STATUS = 'ISSUED'), 
    (SELECT SUM(TABLEB.PROCESS_STATUS) FROM TABLE B WHERE TABLEA.NAME = TABLEB.NAME) 
FROM TABLEA

但它似乎无处可去。请帮帮我......

2 个答案:

答案 0 :(得分:0)

在子查询中执行内部联接并获取已处理状态计数并在外部选择中使用该值

使用case based aggregation获取结果

select A.Component_Type,
       COUNT(A.component_Type) as TOTAL_COMP,
       SUM( case when COMP_STATUS = 'ISSUED' THEN 1 ELSE 0 END ) AS ISSUED_QT,
       MAX(T.COMPLETED_PROCESS_QTY) as COMPLETED_PROCESS_QTY
from tableA A
join ( select A.Component_Type, 
              SUM( case when  PROCESS_STATUS =100 THEN 1 ELSE 0 END) COMPLETED_PROCESS_QTY
       from tableA A
       join TableB B
       on A.name = B.NAME
       group by A.component_Type
       ) T
ON A.Component_Type= T.Component_Type
group by A.component_Type, T.Component_Type
order by A.component_Type desc

答案 1 :(得分:0)

您已声明TABLEA.NAME是PK列。但是示例数据在TABLEA.NAME列中包含重复值。如果这肯定是一个PK列,那么以下查询应该工作,否则结果列COMPLETED_PROCESS_QTY将无法工作。检查一下。

SELECT MAIN_TABLE.COMPONENT_TYPE COMPONENT_RES,
   COUNT(1) TOTAL_COMP,
   (SELECT COUNT(*) FROM TABLEA WHERE COMP_STATUS = 'ISSUED' AND COMPONENT_TYPE = MAIN_TABLE.COMPONENT_TYPE) ISSUED_QTY,
   (SELECT COUNT(*) FROM TABLEA,TABLEB  WHERE TABLEA.NAME = TABLEB.NAME AND PROCESS_STATUS = 100 AND TABLEA.COMPONENT_TYPE = MAIN_TABLE.COMPONENT_TYPE  GROUP BY TABLEA.NAME,TABLEA.COMPONENT_TYPE) COMPLETED_PROCESS_QTY
  FROM TABLEA  MAIN_TABLE
 GROUP BY COMPONENT_TYPE