我有这样的数据:
end date billing
30-NOV-16 0
31-DEC-16 0
31-JAN-17 0
28-FEB-17 208200
31-MAR-17 362950
当我运行此查询时:
SELECT *
FROM
(SELECT
ps.end_date end_date
, ps.itd_gross_billing billing
FROM project_summary_v ps
JOIN projects_dtl pd ON ps.project_id=pd.project_id
JOIN periods_dim xpd ON ps.end_date=xpd.end_date
WHERE pd.project_number=100
FETCH FIRST 6 rows only
)
PIVOT
(
max(billing)
FOR end_date in ( '31-OCT-16'
,'30-NOV-16'
,'31-DEC-16'
,'31-JAN-17'
,'28-FEB-17'
,'31-MAR-17' )
);
我得到以下输出
31-OCT-16 30-NOV-16 31-DEC-16 31-JAN-17 28-FEB-17 31-MAR-17
0 0 0 0 208200 362950
到目前为止一切顺利。但是当我有更多列数据时,
end date billing pd_data mn_data
31-OCT-16 0 10 1
30-NOV-16 0 100 2
31-DEC-16 0 200 3
31-JAN-17 0 90 4
28-FEB-17 208200 30 5
31-MAR-17 362950 50 6
如何转置此表?此外,如果结束日期是动态的(截至目前我已经硬编码) - in()中的查询应该是什么。
输出应该是这样的:
31-OCT-16 30-NOV-16 31-DEC-16 31-JAN-17 28-FEB-17 31-MAR-17
billing 0 0 0 0 208200 362950
pd_data 10 100 200 90 30 50
mn_data 1 2 3 4 5 6
答案 0 :(得分:1)
我认为以下查询可行。我已将查询分隔为pivot。希望这会有所帮助。
SELECT *
FROM
(SELECT ps.end_date end_date ,
ps.itd_gross_billing billing
FROM project_summary_v ps
JOIN projects_dtl pd
ON ps.project_id=pd.project_id
JOIN periods_dim xpd
ON ps.end_date =xpd.end_date
WHERE pd.project_number=100
FETCH FIRST 6 rows only
) pivot( MAX(billing) FOR end_date IN ( '31-OCT-16' ,'30-NOV-16' ,'31-DEC-16' ,'31-JAN-17' ,'28-FEB-17' ,'31-MAR-17' ) )
UNION ALL
SELECT *
FROM
(SELECT ps.end_date end_date ,
ps.pd_data pd_data
FROM project_summary_v ps
JOIN projects_dtl pd
ON ps.project_id=pd.project_id
JOIN periods_dim xpd
ON ps.end_date =xpd.end_date
WHERE pd.project_number=100
FETCH FIRST 6 rows only
) pivot( MAX(pd_data) FOR end_date IN ( '31-OCT-16' ,'30-NOV-16' ,'31-DEC-16' ,'31-JAN-17' ,'28-FEB-17' ,'31-MAR-17' ) )
UNION ALL
SELECT *
FROM
(SELECT ps.end_date end_date ,
ps.mn_data mn_data
FROM project_summary_v ps
JOIN projects_dtl pd
ON ps.project_id=pd.project_id
JOIN periods_dim xpd
ON ps.end_date =xpd.end_date
WHERE pd.project_number=100
FETCH FIRST 6 rows only
) pivot( MAX(mn_data) FOR end_date IN ( '31-OCT-16' ,'30-NOV-16' ,'31-DEC-16' ,'31-JAN-17' ,'28-FEB-17' ,'31-MAR-17' ) )