Maaf jika ini ternyata tidak seperti yang Anda harapkan, tetapi jika Anda hanya perlu menyingkirkan NULL maka saya gagal melihat mengapa Anda tidak bisa melakukan seperti ini:
;WITH CTEterm AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY #term.en, refterm.en
ORDER BY #term.en) AS rownumber,
#term.en AS mainterm,
CHAR(9) + 'SN ' + #term.enscope AS scopenote,
CHAR(9) + #link.reltype + CHAR(32) + refterm.en AS subterms,
CHAR(9) + 'CODE ' + #categorylink.code AS codes
FROM #link
INNER JOIN #term ON #term.termid = #link.termid
INNER JOIN #term AS refterm ON refterm.termid = #link.refid
LEFT JOIN #categorylink ON #term.termid = #categorylink.termid
)
SELECT
AggValue
FROM (
SELECT
mainterm, codes, subterms, scopenote,
COALESCE(
CASE WHEN rownumber = 1 THEN mainterm ELSE NULL END,
scopenote,
subterms,
codes
) AS AggValue
FROM CTEterm
GROUP BY GROUPING SETS ((mainterm, rownumber), (mainterm, scopenote),
(mainterm, subterms), (mainterm, codes))
) s
WHERE AggValue IS NOT NULL
ORDER BY mainterm, codes, subterms, scopenote
Catatan:ELSE NULL
dihapus di sini hanya karena tidak mengubah apa pun (NULL
tersirat ketika tidak ada ELSE
), bukan karena Anda akan mendapatkan apa pun dari menghapusnya.