Break query result in 2 lines

Asked

Viewed 69 times

2

Good afternoon! I have the following question

My query is returning a single line, but I would need it to return two lines, where the first line would be the return of "B" and the other the return of "C"

Any idea how to solve?

select b.*,c.* from portal_sega_user a -- perfil 
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL 
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Thank you.

  • This can help you: https://stackoverflow.com/questions/5641423/how-to-return-multiple-columns-of-the-same-row-in-t-sql-using-group-by ........

3 answers

3


Split the query into two queries and merge with UNION

select b.* from portal_sega_user a -- perfil 
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL 
where a.USUARIO = 'Willian'

UNION 

select c.* from portal_sega_user a -- perfil 
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Note: The number, name and type of the columns must be the same in the two select results, if necessary add alias in the column named selects.

  • Oops! Thank you, that’s exactly what I was trying to do, but I got away using Union. grateful!

2

Make a UNION ALL with two consultations:

SELECT b.*
  FROM portal_sega_user a -- perfil 
 INNER JOIN portal_sega_user b -- secretaria secundaria
    ON b.usuario = a.secretariaprincipal
 INNER JOIN portal_sega_user c -- secretaria secundaria
    ON c.usuario = a.secretariasecundaria
 WHERE a.usuario = 'Willian'
UNION ALL 
SELECT c.*
  FROM portal_sega_user a -- perfil 
 INNER JOIN portal_sega_user b -- secretaria secundaria
    ON b.usuario = a.secretariaprincipal
 INNER JOIN portal_sega_user c -- secretaria secundaria
    ON c.usuario = a.secretariasecundaria
 WHERE a.usuario = 'Willian'

A detail, the use of UNION does not guarantee that your query returns two lines, the UNION ALL yes.

1

Separate your joints and make a union of two Selects:

select b.* from portal_sega_user a -- perfil 
inner join portal_sega_user b  -- secretaria secundaria
on b.USUARIO = a.SECRETARIAPRINCIPAL 
where a.USUARIO = 'Willian'
UNION
select c.* from portal_sega_user a -- perfil 
inner join portal_sega_user c -- secretaria secundaria
on c.USUARIO = a.SECRETARIASECUNDARIA
where a.USUARIO = 'Willian'

Browser other questions tagged

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