簡體   English   中英

子查詢多行時的情況

[英]case when subquery multiple row

我在DB2 9.7.01上有樹表

表A (這里是起始數據)

codeA |type
-----------------------------
P003 |P
K001 |K

表B (這里是產品數據)

codeB |description
-----------------------------
P001 |Product one
P002 |Product two
P003 |Product three

表C (此處為套件數據;套件包括一種或多種產品)

codeC |description |codeB
-----------------------------
K001 |Kit one      |P001
K001 |Kit one      |P002

我需要讀取A表的每條記錄,並且如果字段類型為“ K”,則查詢必須返回其多個乘積; 如果類型為“ P”,則查詢僅返回一種產品; 這是要完成的查詢

Select a.codeA AS codeExternal, 
case 
when a.type = 'K' then (select C.CODEB from C  where A.CODEA = C.CODEC)
 else a.CODEA
end as codeInternal
from 
A 
left B
ON a.CODEA = B.CODEB

但查詢僅返回

codeExt | code Int
---------------------------
P003    | P003
K001    | P001

而不是等待

codeExt | code Int
---------------------------
P003    | P003
K001    | P001
K001    | P002

嘗試這樣的事情:

select A.CodeA CodeExt, B.CodeB CodeInt
from A inner join B on A.CodeA=B.CodeB and A.type='P'
union all
select A.CodeA CodeExt, C.CodeB CodeInt
from A inner join C on A.CodeA=C.CodeC and A.type='K'

如果要刪除doublon,請使用並集而不是全部並集

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM