我试图将结果集放在SQL Developer的pivot中,但看起来查询不正确。你能建议正确的查询来查看数据中的数据。
select *
from(select b.create_date,a.system_serial_number,a.system_status,b.pathway_id,b.ref_trans_id,
row_number() over (partition by b.system_serial_number
order by b.ref_trans_id,b.create_date desc ) R
from eim.eim_pr_system a, eim.eim_pr_system_pathway b
where a.system_serial_number=b.system_serial_number
and a.system_serial_number not in (select system_serial_number
from eim.eim_pr_ib_latest
where role_id = 1
and cmat_customer_id <> -999999)
)
where R=1
pivot (count(system_serial_number) as cnts for (system_status)
in ('ACTIVE' as active,'INACTIVE' as inactive,'DECOMISSIONED' as DECOMISSIONED))
数据:
create_date system_serial_number system_status pathway_id ref_trans_id r
18-Feb-16 2018514 ACTIVE 22 8000646123 1
18-Feb-16 20020615 ACTIVE 22 8000593745 1
18-Feb-16 30009010 ACTIVE 22 8000535738 1
18-Feb-16 30016030 inACTIVE 22 8000594796 1
18-Feb-16 30016718 ACTIVE 20 733187 1
18-Feb-16 30016814 inACTIVE 22 8000515760 1
18-Feb-16 3.0054E+12 ACTIVE 22 8000534021 1
18-Feb-16 3012504 ACTIVE 22 8000432757 1
目前我在excel中执行此操作。在excel中导出和旋转 。 我需要的sql中的预期结果是
Column Labels
Sum of system_serial_number
Row Labels 20 22 Grand Total
ACTIVE 30016718 3.00546E+12 3.00549E+12
inACTIVE 60032844 60032844
Grand Total 30016718 3.00552E+12 3.00555E+12
答案 0 :(得分:0)
请尝试以下代码,看看您是否尝试获得的结果(请注意PIVOT
子句中的差异):
SELECT
system_status "Row Labels",
twenty_cnts "20",
twentytwo_cnts "22",
(nvl(twenty_cnts,0) + nvl(twentytwo_cnts,0)) "Grand Total"
FROM (
SELECT
system_serial_number,
system_status,
pathway_id
FROM (
SELECT
B.create_date,
A.system_serial_number,
A.system_status,
B.pathway_id,
B.ref_trans_id,
row_number() OVER (PARTITION BY B.system_serial_number
ORDER BY B.ref_trans_id, B.create_date DESC) R
FROM
eim.eim_pr_system A,
eim.eim_pr_system_pathway B
WHERE
A.system_serial_number = B.system_serial_number
AND a.system_serial_number NOT IN (SELECT
system_serial_number
FROM
eim.eim_pr_ib_latest
WHERE
role_id = 1
AND cmat_customer_id <> -999999)
)
WHERE
R = 1
)
PIVOT (SUM(system_serial_number) as cnts
FOR (pathway_id) in ('20' twenty, '22' twentytwo)
)