oracle sql中单行常见的多行

时间:2016-05-30 13:42:16

标签: sql oracle rows union-all listagg

我在下面查询,而不是为同一个BN创建多个条目(行),它应该在FC,FM,MS值的同一行创建条目。

select bspt.BN, FC, FM, MS from(select distinct(ozt.BRD_ID),
bp.NAME as BN, 
os.OSS FC, '' FM, '' MS
from PR_BP ozt, PR_BP_BPP bp, BDD b, OS_VIEW os 
where bp.BRD_ID = ozt.BRD_ID AND ozt.BRD_ID = os.OBJECT_ID and 
os.OST = 'PR_BP_BPP' AND (ozt.BID = 10001)
and ozt.BID = b.BID AND ozt.BP_ACTIVE = 'Y'
UNION ALL
select distinct(ozt.BRD_ID),
bp.NAME as BN, 
'' FC, os.OST FM, '' MS
from PR_BP ozt, PR_BP_BPP bp, BRAND b, OS_VIEW os 
where bp.BRD_ID = ozt.BRD_ID AND ozt.BRD_ID = os.OBJECT_ID and 
os.OST = 'PR_BP_BPP' AND (ozt.BID = 10002)
and ozt.BID = b.BID AND ozt.BP_ACTIVE = 'Y'

以上查询生成的输出包含BNAME列的多个条目。因此,它不应创建单独的条目,而应为常见的BNAME创建单行。

1 个答案:

答案 0 :(得分:1)

所有这一切都可以通过一个带有条件聚合的查询来完成。

select bp.NAME as BIZNAME, 
max(case when bbp.BRAND_ID = 10001 then os.OBJECT_STATUS end) FC,
max(case when bbp.BRAND_ID = 10002 then os.OBJECT_STATUS end) FM, 
max(case when bbp.BRAND_ID = 10007 then os.OBJECT_STATUS end) MS 
from PR_BP bbp
JOIN PR_BP_BPP bp ON bp.BP_ID = bbp.BP_ID
JOIN BRAND b ON bbp.BRAND_ID = b.BRAND_ID
JOIN OS_VIEW os ON bbp.BP_ID = os.OBJECT_ID
where os.OBJECT_TYPE = 'PR_BP_BPP' AND bbp.BP_ACTIVE = 'Y'
group by bp.NAME