Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Sql Query para agrupar os dados de duas tabelas


Este:
select final.deptId, d.deptName,
  e3.employeename + ',' + cast(e3.salary as varchar) employee
from employee e3
left join (
  select e1.id, e1.deptId from employee e1
  left join employee e2
  on e1.deptId = e2.deptId and e1.id > e2.id
  where e2.id is null
) final on e3.id = final.id
left join department d on d.id = final.deptId

Resulta em:
+--------+----------+-------------+
| DEPTID | DEPTNAME |  EMPLOYEE   |
+--------+----------+-------------+
|      1 | IT       | John,10000  |
|        |          | Bob,15000   |
|      2 | CSE      | Akon,12000  |
|        |          | Smith,20000 |
+--------+----------+-------------+

Observe que os valores "em branco" são preenchidos com null valores.

Deixe-me saber se você tem algum problema com ele.