哪些值属于两个人

时间:2017-03-07 10:27:45

标签: sql sql-server sql-server-2008

我有这些表格:

Tabel Instrument
Instrument  Pitch
drums       null
guitar      null
paino       null

Tabel Occupation
Stuknr Instrument
1      guitar
2      piano
2      guitar
3      piano
4      drums
4      guitar

Tabel Music
Stuknr ComposerID
1      1
2      1
3      2
4      2

Tabel Composer
ComposerID ComposerName
1          Test1
2          Test2

现在我需要一个查询: 在作曲家的两种音乐中都找到了哪种乐器

我的尝试:

SELECT I.instrumentnaam
FROM Instrument I 
WHERE EXISTS (SELECT 1
          FROM Bezettingsregel B
          WHERE B.instrumentnaam = I.instrumentnaam
          AND EXISTS(SELECT 1
                     FROM Stuk S
                     WHERE S.stuknr = B.stuknr
                     AND EXISTS(SELECT 1
                                FROM Componist C
                                WHERE C.componistId = S.componistId AND C.naam = 'Karl Schumann' OR  C.naam = 'Thom Guidi')))

但这显示了两位作曲家的所有乐器,我只想要两位作曲家都使用的乐器。

Thanx寻求帮助!

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT i.Instrument
FROM Instrument AS i
JOIN Occupation AS o ON i.Instrument = o.Instrument
JOIN Music AS m ON o.Stuknr = m.Stuknr
JOIN Composer AS c ON m.ComposerID = c.ComposerID
GROUP BY i.Instrument
HAVING COUNT(DISTINCT c.ComposerID) = (SELECT COUNT(*)
                                       FROM Composer)

Demo here

答案 1 :(得分:0)

这应该适合您的要求

select distinct Instrument from #Composer a inner join #music b
on a.ComposerID = b.ComposerID inner join #inst c on b.Stuknr = c.Stuknr 
group by Instrument,ComposerName having count(Instrument)>1