Group employees by company in query

Asked

Viewed 97 times

0

I’m making a report, where I need to follow the following layout:

inserir a descrição da imagem aqui

With the query below, we ended up creating more lines, instead of grouping employees per company:

select e.cnpj as cnpj,
       e.nome_completo as empresa,
       li.cod as solicitacao,
       ''  funcionarios
       from liberacoes li,
                  empresa    e
             where
                 li.cnpj = e.cnpj and
                 li.dt_acesso_ini = curdate()
union all

select '' as cnpj,
       '' as empresa,
       '' as solicitacao,
       f.nome_completo as funcionario
                                     from funcionarios f,
                                          empresa      e
                                     where
                                         f.cnpj = e.cnpj
                                     order by 1 desc;

Bringing me that result:

inserir a descrição da imagem aqui

In a query only I can make the output layout equal to what I need to follow?

UPDATE

I tried the query below, but the result is still outside of what I need:

  select
       li.cod,
       e.cnpj,
       e.nome_completo as empresa,
       coalesce(f.nome_completo,'X') as funcionario
   from empresa e
   left outer join funcionarios f on f.cnpj = e.cnpj
   left outer join liberacoes li on li.cnpj = e.cnpj

Upshot:

inserir a descrição da imagem aqui

1 answer

0

you don’t need Union in this case:

   select distinct
       e.cnpj,
       e.nome_completo as empresa,
       coalesce(f.nome_completo,'X') as funcionario
   from empresa e
   left outer join funcionario f on f.cnpj = e.cnpj
  • It didn’t work out buddy, the result was the same.

  • I edited the question, see how the result was.

  • puts the table structure, and try using Sqlfiddle

  • I put a distinct there, make a test

  • Obs. The grouping pro company name appear only once, for n employees, is done at the time of display, so for each employee the company name will appear even in the result of the query

Browser other questions tagged

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