多对多表示为列

时间:2013-07-19 02:05:20

标签: sql-server many-to-many

我有一张代表员工的表。我有第二张表,代表各种员工档案,例如员工,团队负责人,经理,执行等。我有第三个人员将员工映射到多对多关系中的个人资料,即员工可以同时属于“员工”个人资料和“经理人”个人资料。 / p>

如何获得显示第一列中每位员工的回报,然后是代表每个配置文件的后续列,其中是否(或类似)表示该员工是否属于每个特定的个人资料?

2 个答案:

答案 0 :(得分:1)

您可以使用连接和聚合执行此操作:

select e.employee_id,
       max(case when p.profile_name = 'Employee' then 1 else 0 end) as Employee,
       max(case when p.profile_name = 'Manager' then 1 else 0 end) as Manager,
       . . . 
from employees e left outer join
     employee_profile ep
     e.employee_id = ep.employee_id left outer join
     profile p
     on ep.profile_id = p.profile_id
group by e.employee_id;

数据结构本身似乎很合理。

答案 1 :(得分:0)

我认为重新设计是有必要删除你拥有的许多对象。

如果他们有匹配的主/外键,你可以

Select * from Table1, Table2 Where Table1ID = Table2ID