2014-10-20 46 views
0

所以我有这样的两个表,加入两个表中的值和分组它的价值

TABLE1,

NAME COMPONENT QUANTITY STATUS 
NAME1 COLUMN 10  READY 
NAME2 COLUMN 20  READY 
NAME3 COLUMN 15  NOTREADY 
NAME4 COLUMN 10  READY 
NAME5 BEAM  20  NOTREADY 
NAME6 BEAM  15  NOTREADY 
NAME7 BEAM  10  READY 
NAME8 GIRTH  30  NOTREADY 
NAME9 GIRTH  25  NOTREADY 

TABLE2,

NAME PROCESS 
NAME1 5 
NAME2 7 
NAME4 10 
NAME7 8 
在软件这个流程时,该项目

所以没有准备好,它不会在TABLE2中出现。而table2是另一个不同的过程。 什么我期待在我的输出看到的是这样的

COMPONENT_RES COMP_READY COMP_NOT_READY TOTAL_PROCESS 
COLUMN  40   15    22 
BEAM   10   35    10 
GIRTH   0   55    0 

我的财产以后的查询是这样

select distinct md.component COMPONENT_RES, sum(md.quantity) COMP_READY, 
(select sum(md.quantity) COMP_NOT_READY from table1 md where md.status = 'NOTREADY') 
from table1 md where md.status = 'ACTIVE' 
group by md.component 

somethins我在这里有2个问题, 1.我的询问不工作的条件分离COMP_READY和COMP_NOT_READY 2.我尝试了百万次,当GIRTH不存在但必须显示为0时,如何从第二个表中整合TOTAL_PROCESS。

感谢gu YS

回答

0

你需要做两个聚合和结果结合在一起:

select c.component, c.comp_ready, c.comp_notready, cp.total_process 
from (select component, 
      sum(case when status = 'READY' then Quantity else 0 end) as Comp_Ready, 
      sum(case when status = 'NOTREADY' then Quantity else 0 end) as Comp_NotReady, 
     from table1 
     group by component 
    ) c left join 
    (select t1.component, sum(t2.component) as total_process 
     from table1 t1 join 
      table2 t2 
      on t1.name = t2.name 
     group by t1.component 
    ) cp 
    on c.component = cp.component; 

诀窍是,第二子查询,以获得相应的组件需要join

+0

真棒...感谢戈登 – 2014-10-21 03:45:46

+0

我不知道为什么这是downvoted。 – 2014-10-21 09:33:36

+0

我没有downvoted这个... – 2014-10-23 03:39:23

1

你需要的是一个表之间的OUTER JOIN。

SQL Fiddle

查询1

select 
table1.component_, 
sum(case when table1.status_ = 'READY' then table1.quantity else 0 end) comp_ready, 
sum(case when table1.status_ = 'NOTREADY' then table1.quantity else 0 end) comp_notready, 
sum(coalesce(table2.process_,0)) total_process 
from table1 left outer join table2 
on table1.name_ = table2.name_ 
group by table1.component_ 

Results

| COMPONENT_ | COMP_READY | COMP_NOTREADY | TOTAL_PROCESS | 
|------------|------------|---------------|---------------| 
|  COLUMN |   40 |   15 |   22 | 
|  GIRTH |   0 |   55 |    0 | 
|  BEAM |   10 |   35 |    8 | 
+0

它运作得很好..我的问题是,我如何添加另一个表?这是否意味着我需要一个左外侧奥乔恩? – 2014-10-21 04:11:23

+0

这取决于。如果你只想要通用记录使用内连接。如果您还想包含不匹配的记录,请使用外连接。 – Noel 2014-10-21 04:16:53