我写了一些代码来检索名为ADMR代码的学生入学信息(' IMMU',' HST1',' RCEC'' TEST&# 39;) - 代码没有错误并生成报告。验证数据时的报告中报告中缺少数据。我在报告中遗漏了ADMR代码的一些数据 - 我更改了行号()函数中的值,这会更改结果,但结果仍然不正确。代码读取每个ADMR代码每个学生有多行的表...我想在我的报告中没有多行,而是根据学生将所有ADMR代码放在他们自己的列中 - 输出示例:
Student_ID IMMU HST1 RCEC TEST
51738 08-JUN-09
51811 27-APR-17 27-APR-17
51965 12-APR-17 07-APR-17
提前感谢您提供任何输入
守则如下:
select admr_code.pidm,
max(case when admr_code.position = 1 and admr_code.admr = 'HST1' then admr_code.rec_date end)HST1,
max(case when admr_code.position = 2 and admr_code.admr = 'IMMU' then admr_code.rec_date end)IMMU,
max(case when admr_code.position = 3 and admr_code.admr = 'RCEC' then admr_code.rec_date end)RCEC,
max(case when admr_code.position = 4 and admr_code.admr = 'TEST' then admr_code.rec_date end)TEST
from
(select
sarchkl_pidm pidm,
sarchkl_term_code_entry term,
sarchkl_admr_code admr,
sarchkl_receive_date rec_date,
row_number() over(partition by sarchkl_pidm order by sarchkl_pidm asc) position
from sarchkl
where sarchkl_term_code_entry = '201750' and
sarchkl_admr_code IN ('HST1','IMMU','RCEC','TEST')
)admr_code
Group By admr_code.pidm
order by admr_code.pidm
答案 0 :(得分:0)
这是T-SQL,但PL-SQL语法应该非常相似。我现在没有Oracle进行测试。
如果列出了多个日期,PIVOT会在您需要的列下为您提供所需的日期而不会重复。在我的测试数据中,我添加了一个欺骗日期行和一些应该从最终查询中排除的其他错误数据。
/* CTE for test data */
; WITH sarchkl AS (
SELECT 51738 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'IMMU' AS sarchkl_admr_code, '20090608' AS sarchkl_receive_date UNION ALL
SELECT 51738 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'IMMU' AS sarchkl_admr_code, '20001231' AS sarchkl_receive_date UNION ALL
SELECT 51738 AS sarchkl_pidm, '201740' AS sarchkl_term_code_entry, 'IMMU' AS sarchkl_admr_code, '20090608' AS sarchkl_receive_date UNION ALL
SELECT 51811 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'HST1' AS sarchkl_admr_code, '20170427' AS sarchkl_receive_date UNION ALL
SELECT 51811 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'RCEC' AS sarchkl_admr_code, '20170427' AS sarchkl_receive_date UNION ALL
SELECT 51965 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'IMMU' AS sarchkl_admr_code, '20170412' AS sarchkl_receive_date UNION ALL
SELECT 51965 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'FAKE' AS sarchkl_admr_code, '20170101' AS sarchkl_receive_date UNION ALL
SELECT 51965 AS sarchkl_pidm, '201750' AS sarchkl_term_code_entry, 'TEST' AS sarchkl_admr_code, '20170407' AS sarchkl_receive_date
)
/* QUERY */
SELECT b.sarchkl_pidm AS pidm, b.HST1, b.IMMU, b.RCEC, b.TEST
FROM (
SELECT sarchkl_pidm, sarchkl_admr_code, sarchkl_receive_date
FROM sarchkl
WHERE sarchkl_term_code_entry = '201750'
AND sarchkl_admr_code IN ('HST1','IMMU','RCEC','TEST')
) a PIVOT (
max(sarchkl_receive_date)
FOR sarchkl_admr_code
IN (HST1,IMMU,RCEC,TEST)
) b
ORDER BY pidm
我在查询中添加了别名,以说明列的来源。如果你想太多,PIVOT会伤到你的头,但它们是一个很好的工具。