Lo siento si esto no resulta realmente lo que esperabas, pero si simplemente necesitas deshacerte de los valores NULL, no veo por qué no puedes hacer esto:
;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
se elimina aquí solo porque no cambia nada (NULL
está implícito cuando no hay ELSE
), no porque ganaría algo al eliminarlo.