ORG_ITEM表包含重复的ID。这些ID显示相同ID的不同MFR和PART_NO。这导致我的查询返回具有相同ID的多个行。如何将这些行放入一行,每个MFR和PART_NO作为一个单独的列?
SELECT
PART_LOC.CLASS,
PART_LOC.ID,
ORG.MFR,
ORG_ITEM.PART_NO,
PART_LOC.STORAGE_LOC,
PART_LOG.QTY,
COST.UNIT_COST
FROM
PART_LOC
LEFT JOIN COST on PART_LOC.ID = COST.ID
LEFT JOIN ORG_ITEM on PART_LOC.ID = ORG_ITEM.ID
LEFT JOIN ORG on ORG_ITEM.MFR = ORG.MFR
WHERE
PART_LOC.STORAGE_LOG = :Facility
目前返回:
CLASS ID MFR PART_NO STORAGE_LOC QTY COST
3 1234 Grainger 123F6 CRIB 6 12.67
3 1234 Hagerty asd45 CRIB 6 12.67
3 1234 MSC poi98 CRIB 6 12.67
希望它返回:
CLASS ID MFR-PART_NO1 MFR-PART_NO2 MFR-PART_NO3 STORAGE_LOC QTY COST
3 1234 Grainger-123F6 Hagerty-asd45 MSC-poi98 CRIB 6 12.67
答案 0 :(得分:0)
你可以尝试这样的事情。对于每个ID,我假设最多有五个制造商。我还假设你并不关心制造商的展示顺序。如果您关心(例如,如果您希望它们在每行中从左到右按字母顺序排列),您可以在我添加到内部查询的ROW_NUMBER()函数中添加排序条件;现在它显示"按null排序" (这意味着你对命令漠不关心。)
如果每个ID超过五个制造商,此查询仍然有效;输出中只显示五个制造商(六个,八个或十个)。
select class, id, mfr_part1, mfr_part2, mfr_part3, mfr_part4, mfr_part5,
storage_loc, qty, unit_cost
from (
SELECT
PART_LOC.CLASS,
PART_LOC.ID,
ORG.MFR,
ORG_ITEM.PART_NO,
PART_LOC.STORAGE_LOC,
PART_LOG.QTY,
COST.UNIT_COST,
row_number() over (partition by part_loc.id order by null) as RN
FROM
PART_LOC
LEFT JOIN COST on PART_LOC.ID = COST.ID
LEFT JOIN ORG_ITEM on PART_LOC.ID = ORG_ITEM.ID
LEFT JOIN ORG on ORG_ITEM.MFR = ORG.MFR
WHERE
PART_LOC.STORAGE_LOG = :Facility
)
pivot ( max(mfr || '-' || part_no)
for RN in (1 as mfr_part1, 2 as mfr_part2, 3 as mfr_part3,
4 as mfr_part4, 5 as mfr_part5)
)
;