简体   繁体   English

组织结构图SQL查询

[英]Org Chart SQL Query

I am trying to create a table to hold an org chart using SQL Server but have not been successful so far.我正在尝试使用 SQL 服务器创建一个表格来保存组织结构图,但到目前为止还没有成功。 I have tried doing sub-selects and self-joins but I can't get the desired output.我尝试过进行子选择和自连接,但无法获得所需的 output。

This is what the table looks like today, showing who reports to who:这是今天的表格,显示了谁向谁报告:

1    2         3
Bob  Jon     Kevin
Bob  Mark    Paul
Bob  Jon     Ian

My desired outcome is to show all resources in one column, and then display the org chart to the right, like this:我想要的结果是在一列中显示所有资源,然后在右侧显示组织结构图,如下所示:

Resource    3        2       1
Kevin      Kevin    Jon     Bob
Paul       Paul     Mark    Bob
Ian        Ian      Jon     Bob
Jon        NULL     Jon     Bob
Mark       NULL     Mark    Bob
Bob        NULL     NULL    Bob

I am not sure if this is possible with SQL or what strategies I should use to accomplish it.我不确定 SQL 是否可行,或者我应该使用什么策略来完成它。 Pivots, CTEs, etc.枢轴、CTE 等

You can use apply to unpivot and then use select distinct to remove duplicates:您可以使用apply到 unpivot 然后使用select distinct删除重复项:

select distinct v.*
from t cross apply
     (values (col3, col3, col2, col1),
             (col2, col2, col1, null),
             (col1, col1, null, null)
     ) v(resource, col3, col2, col1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM