Scusa se questo non è proprio quello che ti aspettavi, ma se hai semplicemente bisogno di sbarazzarti dei NULL, non riesco a capire perché non puoi semplicemente fare così:
;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
Nota:ELSE NULL
viene rimosso qui solo perché non cambia nulla (NULL
è implicito quando non c'è ELSE
), non perché guadagneresti qualcosa rimuovendolo.