Union All specify select no order by

Asked

Viewed 84 times

0

I have ONE test table and I’m doing a Union All and I want to sort by date but not sort by the first select before Union All which would be a headline. I would like to order only the data of the second select, could you help me? The first select should be fixed to the first row as it is like a description of the column.

SELECT

'NOME_FUNCIONARIO',
'DATA_FUNCIONARIO' 

UNION ALL

SELECT NOME
        ,CONVERT(VARCHAR,DATA,106) 

        FROM B
        ORDER BY 2
  • So that this header !?

  • If the ORDER BY clause should apply to only one of the SELECT participating in the UNION then use parentheses, otherwise it will apply to the UNION result. In your case put the second SELECT in parentheses.

2 answers

2


Almino, I do not know if you will get the lines in the expected order if you are (as it seems) converting the date into a format that is not year, month and day, but anyway, follow a suggestion for tests:

SELECT
  'NOME_FUNCIONARIO',
  'DATA_FUNCIONARIO',
  0
  
UNION ALL

SELECT
  NOME,
  CONVERT(VARCHAR,DATA,106),
  1
FROM B

ORDER BY 3, 2

I hope it helps

  • Thanks worked out!

1

Include a column to carry out the order by select and sort so first, the rest is the same.

SELECT NOME, DATA
  FROM (SELECT 'NOME_FUNCIONARIO' nome, 'DATA_FUNCIONARIO' DATA, 1 ordem
        UNION ALL
        SELECT NOME ,CONVERT(VARCHAR,DATA,106), 2 ordem
          FROM B
         ORDER BY 3, 2)
  • 1

    Thank you, I tested it that way and it worked too

Browser other questions tagged

You are not signed in. Login or sign up in order to post.