我有一个包含三列的表格: EmployeeID ,部门,位置
每位员工可能拥有多个部门,并且可以位于多个位置。
通过SQL查询任何RDBMS, 我需要返回不同的Departments集合(用连字符分隔),不同的Locations集合(用连字符分隔)对每个EmployeeID。
对于DB中的以下记录,
EMP1,HR,Kolkata
EMP1,HR,Delhi
EMP1,Facility,Mumbai
EMP1,Facility,Kolkata
我需要得到以下结果:EMP1,HR-Facility,Kolkata-Delhi-Mumbai
任何帮助都将受到欢迎。
答案 0 :(得分:1)
我能想到在ANSI SQL中执行此操作的唯一方法是使用dense_rank()
和条件聚合。假设每组的值不超过三个:
select empid,
trim(trailing '-' from
concat( max(case when l_seqnum = 1 then concat(location, '-') else '' end),
max(case when l_seqnum = 2 then concat(location, '-') else '' end),
max(case when l_seqnum = 3 then concat(location, '-') else '' end)
) as locations,
trim(trailing '-' from
concat( max(case when d_seqnum = 1 then concat(department, '-') else '' end),
max(case when d_seqnum = 2 then concat(department, '-') else '' end),
max(case when d_seqnum = 3 then concat(department, '-') else '' end)
) as departments
from (select t.*,
dense_rank() over (partition by empid order by department) as d_seqnum,
dense_rank() over (partition by empid order by location) as l_seqnum
from table t
) t
group by empid;
但是,大多数数据库都有更合理的方式来表达这一点。