从同一表获取结果集以进行树形视图

时间:2018-11-03 23:04:25

标签: sql sql-server tsql select distinct

我正在尝试通过从下表中获取数据来实现树形视图,以下所有ID都是varchars:

     user_id   name  R_id R_name  mgr_id   mgr_name
     ----------------------------------------------
     61        a     64    c       65       b
     62        a     66    c       65       b
     63        b     64    c       65       b
     64        c     65    b       65       b
     65        b     NULL  NULL    NULL     NULL
     66        c     65    b       65       b

R_id,mgr_id依次在同一表中的用户列中 现在,我想获得以下结果集:

   user_id      name     Parent
   ----------------------------
   65           b         NULL
   66           c         65
   64           c         65
   63           b         64
   62           a         66
   61           a         64

这是我正在使用的查询,但看起来有点复杂,我敢肯定应该有一个更简单的方法来处理这个问题:

    CREATE TABLE #DT
   (
    user_id VARCHAR(10),
    name VARCHAR(100),
    parent VARCHAR(10)
   )

INSERT INTO #DT
SELECT DISTINCT 
    mgr_id as user_id,
    mgr_name as name ,
    NULL AS parent 
FROM 
    Users

INSERT INTO #DT
SELECT DISTINCT 
    user_id as user_id,
    name as name ,
    mgr_id AS parent   
FROM
    Users

INSERT INTO #DT
SELECT DISTINCT
    mgr_id as user_id,
    mgr_name as name ,
    R_id AS parent 
FROM
    Users

SELECT  * FROM #DT

2 个答案:

答案 0 :(得分:0)

为此使用UNION。默认情况下,UNION有效地已经应用了SELECT DISTINCT。您还只需要在第一个SELECT语句上应用列别名。

SELECT mgr_id AS user_id, mgr_name AS name, NULL AS parent FROM Users
UNION
SELECT user_id, name, mgr_id FROM Users
UNION
SELECT mgr_id, mgr_name, R_id FROM Users

答案 1 :(得分:0)

您的原始查询会带来重复项,因为DISTINCT仅应用于每个查询,而不应用于整个结果。如果这对您很重要,则可以使用(DEMO

SELECT v.user_id,
       v.name,
       v.parent
FROM   users
       CROSS apply (VALUES (1,mgr_id,mgr_name,NULL),
                           (2,user_id,name,mgr_id),
                           (3,mgr_id,mgr_name, R_id) ) v(source, user_id, name, parent)
GROUP  BY v.source,
          v.user_id,
          v.name,
          v.parent 

否则,删除这些的更简单的版本是

SELECT DISTINCT v.user_id,
                v.name,
                v.parent
FROM   users
       CROSS apply (VALUES (mgr_id,mgr_name,NULL),
                           (user_id,name,mgr_id),
                           (mgr_id,mgr_name, R_id) ) v(user_id, name, parent)