Order by with Union

Asked

Viewed 2,210 times

0

I have the following tables:

Pessoa1
Id  |    Nome      |  Cidade
1   |   José       |São Paulo
2   |   Maria      |Rio de Janeiro

Pessoa2
Id  |    Nome      |  Cidade
1   |   Pedro      |Belo Horizonte
2   |   Ana        |Vitória

I have the following select:

SELECT * FROM (

    SELECT
          p1.Nome
          ISNULL(CAST(p1.Nome AS VARCHAR),'') + ';' + 
          ISNULL(CAST(p1.Cidade AS VARCHAR),'') AS Resultado
    FROM Pessoa1 p1

    UNION

    SELECT
          p2.Nome
          ISNULL(CAST(p2.Nome AS VARCHAR),'') + ';' + 
          ISNULL(CAST(p2.Cidade AS VARCHAR),'') AS Resultado
    FROM Pessoa1 p2

) AS Resultado
ORDER BY Resultado.Nome

The goal is to bring the column Resultado with values separated by semicolon, respecting the alphabetical order through the column Nome.

The point is that I would like the column Nome did not appear when executing the select, because it is already included in the column Resultado. Is there any way?

1 answer

5


You are using the dial *, which means all fields. Change your SQL from:

SELECT * FROM (

for

SELECT Resultado FROM (

So only this field will be returned.

  • How have I not seen this before?! Thank you very much! Lack of attention from me...

  • I thought about it, but that alone would order the result by the column Nome ?

  • @Dontvotemedown not, but the last part of the statement is: ORDER BY Resultado.Nome, thus guaranteeing the ordination.

  • 1

    @Jedaiasrodrigues without stress, happens to the best among us. =)

Browser other questions tagged

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