2017-03-10 31 views
1

Tbl_family两个内部联接与条件不工作

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

tbl_childparent

#Child_id Parent_id 
1 2 
1 3 
4 5 
4 6  

我想这需要显示childID的,ChildName,父亲,母亲 这是我的SQL查询,但是它不一个输出“科技工作

SELECT tf2.ID,tf2.Name AS ChildName,tf.Name AS Father,tf3.Name AS Mother 
FROM dbo.tbl_clildparent tc 
INNER JOIN dbo.tbl_Family tf ON tc.Parent_id=tf.ID 
    AND tf.Gender='M' 
INNER JOIN dbo.tbl_Family tf3 ON tc.Parent_id = tf3.ID 
    AND tf3.Gender='F' 
LEFT OUTER JOIN dbo.tbl_Family tf2 ON tc.Child_id = tf2.ID 
+1

我们怎么知道哪个母亲或父亲属于哪个孩子?我在你的数据中没有看到这种关系。 –

+0

检查tbl_child父表,它显示了孩子ID和父母,并根据性别我们需要父母亲 – RCY

+0

这可能有一个孩子的父母(父亲和母亲)的两个记录? –

回答

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 

OUTPUT:

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

谢谢..但是当我用两个内部在查询中加入一个tc.Parent_id到tbl_Family不同条件(包括“M”和“F”)加入 – RCY

+0

为什么不工作我的代码。如果两个条件都满足,那么只有你会得到结果,在这里它不会发生。 –

+0

做一件事,只要将你所有的INNER连接变成你的查询中的LEFT OUTER JOIN,你现在就会得到更好的理解。 –

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 

OUTPUT:

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

感谢它的工作.. – RCY

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 
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'