从子查询,SQL,求解中选择行

时间:2016-01-13 14:39:41

标签: sql sql-server database

无论我尝试什么,我似乎无法做到这一点:所以基本上我有这个表的例子:

 table: HOTEL
 HID    NAME
 ----------------------- 
 H1     HILTON     
 H2     MOUNTAIN INN
 H3     TROPICANA


 table: Renting
 ID     JMBG   HID 
 -----------------------
 1      J2     H1
 2      J2     H2
 3      J2     H3
 4      J1     H1


 table: Clijents
 JMBG    NAME
 -----------------------
 J1      ALICE
 J2      JOHN

从这里开始,我应该找到所有租给所有klients的酒店,或者在这种情况下只是 H1 这是我最好的尝试,我没有工作;(

    SELECT HID FROM HOTEL H
WHERE H.HID IN
     (select HID, COUNT(DISTINCT ID) AS RENTED
        FROM RENTINGS R
        GROUP BY R.HID )
   AND R.RENTED=(SELECT COUNT(*) FROM CLIJENTS )

1 个答案:

答案 0 :(得分:2)

  • 如果一家酒店多次租给同一客户,您需要count(distinct)

SELECT HID
FROM Renting 
GROUP BY HID
HAVING COUNT (DISTINCT JMBG) =  (SELECT COUNT(*) FROM CLIJENTS )