两个内连接条件不起作用

时间:2017-03-10 04:15:39

标签: sql sql-server

Tbl_family

<configuration>
<config> 
    <add key="dependencyversion" value="Highest" /> 
</config>

tbl_childparent

#ID Name    Gender
1   Ram M         
2   Sasank  M         
3   Maya    F         
4   Manu    F         
5   Anu F         
6   Raj M  

我想要一个需要显示ChildID,ChildName,Father,Mother的输出 这是我的SQL查询,但它不起作用

#Child_id   Parent_id
1   2
1   3
4   5
4   6       

4 个答案:

答案 0 :(得分:2)

尝试这个:您可以使用CASEGROUP BY获得所需的输出,如下所示:

select tf.id AS ChildID, tf.Ename AS ChildName, 
    Max(case when tfp.gender = 'm' then tfp.Ename end) Father, 
    MAX(case when tfp.gender = 'f' then tfp.Ename end) Mother
from #tbl_childparent tc
left join #tbl_Family tf on tc.child_id = tf.id
left join #tbl_Family tfp on tc.parent_id = tfp.id
group by tf.id, tf.Ename

<强>输出:

ChildID ChildName   Father  Mother
4       Manu        Raj     Anu 
1       Ram         Sasank  Maya    

答案 1 :(得分:1)

尝试以下查询

SELECT  Child_id,N.Name,
        MAX((CASE WHEN F.Gender = 'M' THEN F.Name ELSE NULL END )) AS Father,
        MAX((CASE WHEN M.Gender = 'F' THEN M.Name ELSE NULL END )) AS Mother
FROM    @tbl_childparent    AS  C
    INNER JOIN  @Tbl_family AS  N   ON  N.ID    =   C.Child_id
    LEFT JOIN @Tbl_family   AS  F   ON  F.ID    =   C.Parent_id
    LEFT JOIN @Tbl_family   AS  M   ON  M.ID    =   C.Parent_id
GROUP BY Child_id,N.Name

输出:

Child_id    Name    Father  Mother
1           Ram     Sasank  Maya
4           Manu    Raj     Anu

答案 2 :(得分:0)

SELECT Id,ChildName,
MAX(CASE WHEN Gender='M' THEN Father END)Father,
MAX(CASE WHEN Gender='F' THEN Mother END)Mother 
FROM (
SELECT tf2.ID,tf2.Name AS ChildName,tf.Name AS Father,tf.Name AS Mother,tf.Gender
FROM #TEMP1 tc
INNER JOIN #TEMP tf ON tc.Parentid=tf.ID 
LEFT JOIN #TEMP tf2 ON tc.Childid = tf2.ID
)A GROUP BY Id,ChildName

答案 3 :(得分:0)

with cte as
(
select cp.Child_ID, c.Name as 'ChildName' 
cp.Parent_ID, p.Name as 'ParentName', p.Gender as 'ParentGender'
from tbl_childparent cp
join Tbl_family p on cp.Parent_ID = p.ID
join Tbl_family c on cp.Child_ID = c.ID
)

select t1.CHildID, t1.ChildName, t1.ParentName as Father, t2.ParentName as Mother from cte t1
join cte t2 on t1.child_id = t2.child_ID
where t1.ParentGender = M and t2.ParentGender = 'F'