SELECT从Parent继承值(自引用)

时间:2017-08-21 20:21:03

标签: sql-server common-table-expression self-referencing-table

我有02桌Rubrique和BulletinRubrique 表Rubrique包含以下列:

ID int not null,
Name, varchar(max) not null,
RubriqueA_ID int null,
RubriqueB_ID int null

以数据为例:

+-------+---------+--------------+--------------+
| ID    | Name    | RubriqueA_ID | RubriqueB_ID | 
+-------+---------+--------------+--------------+
| 1     | R1      |    2         |    3         |
| 2     | R2      |    1         |    2         |
| 3     | R3      |    NULL      |    NULL      |
| 4     | R4      |    NULL      |    6         |
| 5     | R5      |    6         |    NULL      |
| 6     | R6      |    NULL      |    1         |
+-------+---------+--------------+--------------+

两列RubriqueA_IDRubriqueB_ID是同一个表Rubrique(自引用)的foreigns键,它们可能为NULL

BulletinRubrique

ID int not null,
EmployeID int not null,
RubriqueID int not null,
Value float not null

有数据:

+-------+-----------+--------------+------------+
| ID    | EmployeID | Rubrique_ID  | Value      | 
+-------+-----------+--------------+------------+
| B1    | EMP1      | 1            | 150        |
| B1    | EMP1      | 2            | 220        |
| B1    | EMP1      | 3            | 195        |
| B1    | EMP1      | 4            | 170        |
| B1    | EMP1      | 5            | 320        |
| B1    | EMP1      | 6            | 745        |
+-------+-----------+--------------+------------+

我想要做的是建立sql查询以获得结果:

+-------+-----------+--------------+------------+----------+---------+
| ID    | EmployeID | Rubrique_ID  | Value      | A_Value  | B_Value |
+-------+-----------+--------------+------------+----------+---------+
| B1    | EMP1      | 1            | 150        | 220      | 195     |
| B1    | EMP1      | 2            | 220        | 150      | 220     |
| B1    | EMP1      | 3            | 195        | NULL     | NULL    |
| B1    | EMP1      | 4            | 170        | NULL     | 745     |
| B1    | EMP1      | 5            | 320        | 745      | NULL    |
| B1    | EMP1      | 6            | 745        | NULL     | 150     |
+-------+-----------+--------------+------------+----------+---------+

请帮我构建此查询并感谢

2 个答案:

答案 0 :(得分:3)

http://rextester.com/FIJE42564是工作代码

fork

答案 1 :(得分:1)

作为嵌套CTE的粉丝,这就是我尝试解决这个问题的方法

WITH CTE1 as(
SELECT 
    BR.Id, BR.EmployeID, BR.RubriqueID, BR.value, R1.Rubriquea_Id, R2.Rubriqueb_Id 
FROM 
    BulletinRubrique BR
LEFT JOIN 
    Rubrique R1 ON R1.Id = BR.RubriqueID
LEFT JOIN 
    Rubrique R2 ON  R2.Id = BR.RubriqueID
),
CTE2 as (
SELECT 
    C1.Id, C1.EmployeID, C1.RubriqueID, C1.value, C2.value as A_Value, C3.value as B_Value 
FROM 
    CTE1 C1
LEFT JOIN 
    CTE1 C2 ON C1.Rubriquea_Id = C2.RubriqueID
LEFT JOIN 
    CTE1 C3 ON  C1.RubriqueB_Id = C3.RubriqueID
)
SELECT C1.Id, 
    C1.EmployeID, 
    C1.RubriqueID, 
    C1.value,
    C1.A_Value as A_Value, 
    C1.B_Value as B_Value  FROM CTE2 C1
ORDER BY Id