I have the following query that gives me the error:
SELECT DISTINCT ORDER BY elements must appear in the select list
SELECT
DISTINCT
(RIGHT('00000' + LTRIM(RTRIM(Grupo)), 5) + RIGHT('000' + LTRIM(RTRIM(SubGrupo)), 3)) AS Grupo, SubGrupo, NombreSubGrupo
FROM DBTABLA
ORDER BY Grupo + 0
The mistake is clear.
Grupo + 0
does not exist in the select list.When using a derived table, it does not apply the
distinct
, and you can order by the criteria that seems appropriate to you.In the end I solved it like this: