所以我有这两张桌子,
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
我这里有两个问题, 1.我的查询在分离COMP_READY和COMP_NOT_READY方面不起作用 2.当GIRTH不存在但是必须显示为0时,我尝试了数百万次如何从第二个表中集成TOTAL_PROCESS。
谢谢你们
答案 0 :(得分:1)
您需要的是表之间的OUTER JOIN。
查询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 |
答案 1 :(得分: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
才能获得适当的组件。