2016-11-01 7 views
0

を見つけるために、それ自体の上にテーブルを結合私はこのようなテーブルを持っている:SQL - 同じ親を持つ人々に

*Id, Name, Surname, Father Name, Mother Name 
--------------------------------------------- 
*1, John, Green, James, Sue 
*2, Michael, Sloan, Barry, Lilly 
*3, Sally, Green, Andrew, Molly 
*4, Michael, Sloan, Barry, Lilly 
*5, Ned, White, James, Sue 

私は与えられた最初の名前の同じ父親の名前と母の名を持つ行を選択する問合せをしたいです。私は同じ両親とジョンズとNeDSのを選択したい場合などのテーブルについては、クエリが

1, John, Green, James, Sue 
5, Ned, White, James, Sue 

を返す必要があり、私は自分自身でテーブルを結合してみましたが、私はどこに基準を変更する方法に関係なく、それはデカルト積を返しました。任意のヒント?

+0

これを試すことができます使用しているデータベースであなたの質問にタグを付けてください。 –

+0

これまでに試したこと –

+0

十分明確ではありません。 '6 Ned、Blue、Roger、Lucy --- 7、John、Black、Roger、Lucy --- 8、Ned、Orange、Ben、 Still' –

答えて

0

リレーショナル分裂と呼ばれている必要があるものを使用したサブクエリ

SELECT * FROM Table 
WHERE (FatherName, MotherName) IN 
(SELECT FatherName, MotherName FROM Table WHERE Name='John') 
0

。しかし、通常は集計されたデータが返され、テーブルからすべての行が必要になるため、あなたの場合はややこしいです。だから、確かに、自己の参加が必要です。サブクエリで

select t.* 
from dbo.Table t 
    inner join (
    select d.FatherName, d.MotherName 
    from dbo.Table d 
    group by d.FatherName, d.MotherName 
    having count(*) > 1 
) sq on sq.FatherName = t.FatherName 
    and sq.MotherName = t.MotherName; 

を、あなたは、テーブル内の1つのエントリよりも多くを持っているだけFather+Mother組み合わせを選択して、これらの親からの出力すべてに再びテーブルでそれに参加します'ペア。

0

この場合、自己結合が適切な方法です。

SELECT DISTINCT t1.* 
FROM MyTable AS t1 
INNER JOIN MyTable AS t2 
    ON t1.FatherName=t2.FatherName 
    AND t1.MotherName=t2.MotherName 
    AND t1.Id<>t2.Id 
WHERE t1.Name in ('John', 'Ned') 
+0

同じ親に3人の子供がいる場合、3行すべてが出力に複製されます。 –

+0

あなたは正しいです、「別個」がそれをより良くするはずです。 – alreadythere

0

あなたは(group bycount(*)なし)

with fm as 
(select fathername, mothername,row_number() over (partition by fathername,  
mothername order by id) rownum 
from #tmp1 
) 
select b.* 
from #tmp1 b 
join fm 
on b.fathername = fm.fathername 
and b.mothername = fm.mothername 
where fm.rownum = 2 
関連する問題