我不知道,知道爲什麼這樣做這種方式,但你可以使用:
WITH tab_row_num AS (
SELECT row_number() over (PARTITION BY "SemesterId") rn, "SemesterId" , "Course" , "Grade" FROM table1
),
joint_tab AS (
select
t1_3."SemesterId" AS "SemesterId1", t1_3."Course" as "Course1" , t1_3."Grade" as "Grade1",
t2_4."SemesterId" AS "SemesterId2", t2_4."Course" as "Course2" , t2_4."Grade" as "Grade2"
from tab_row_num t1_3
full outer join tab_row_num t2_4
ON (t1_3."SemesterId" = 1 AND t2_4."SemesterId"=2 AND t1_3.rn=t2_4.rn)
OR (t1_3."SemesterId" = 3 AND t2_4."SemesterId"=4 AND t1_3.rn=t2_4.rn)
)
SELECT
COALESCE("SemesterId1"::TEXT, '') , COALESCE("Course1"::TEXT, '') , COALESCE("Grade1"::TEXT, ''),
COALESCE("SemesterId2"::TEXT, '') , COALESCE("Course2"::TEXT, '') , COALESCE("Grade2"::TEXT, '')
FROM (
SELECT *
FROM (
SELECT "SemesterId1" , "Course1" , "Grade1", "SemesterId2" , "Course2" , "Grade2"
FROM joint_tab t
WHERE (t."SemesterId1" = 1 OR t."SemesterId1" IS NULL) AND (t."SemesterId2" = 2 OR t."SemesterId2" IS NULL)
ORDER BY "SemesterId1" NULLS LAST, "Course1" ASC, "Grade1" ASC, "SemesterId2" NULLS LAST, "Course2" ASC, "Grade2" ASC
) sub1
UNION ALL
SELECT * FROM (
SELECT "SemesterId1" , "Course1" , "Grade1", "SemesterId2" , "Course2" , "Grade2"
FROM joint_tab t WHERE (t."SemesterId1" = 3 OR t."SemesterId1" IS NULL) AND (t."SemesterId2" = 4 OR t."SemesterId2" IS NULL)
ORDER BY "SemesterId1" NULLS LAST, "Course1" ASC, "Grade1" ASC, "SemesterId2" NULLS LAST, "Course2" ASC, "Grade2" ASC
) sub2
) sub
你是認真的嗎? – mikus
通過將數據複製到具有所需佈局的(excel)電子表格中。 – Filburt
@mikus我會對Anusha所採用的方法有嚴重的擔憂 - 這絕對要求在表示層中實現。但是,如果我們用SQL去 - 我想知道 - 它真的很明顯,我錯過了如何編碼? –