我有两张桌子:Car和CarBorrowed。
汽车表包含汽车池中的所有汽车,其中包含汽车所属的ID和组。例如:
ID 1, Car 1, Group Renault
ID 2, Car 3, Group Renault
ID 3, Car 4, Group VW
ID 4, Car 6, Group BMW
ID 5, Car 7, Group BMW
CarBorrow 表包含在特定日期借用的所有汽车
Car 1, Borrowed on 23.08.2012
Car 3, Borrowed on 23.08.2012
Car 5, Borrowed on 23.08.2012
现在我想要所有没有车辆的团体(今天= 23.08.2012)。所以我应该得到“雷诺集团”
答案 0 :(得分:1)
select borrowed.BorrowedOn, available.CarGroup
from (select c.CarGroup, count(*) as cnt
from car c
group by c.CarGroup
) available left outer join
(select c.CarGroup, cb.BorrowedOn, count(*) as cnt
from CarBorrowed cb join
Car c
on cb.CarId = c.CarId
group by c.CarGroup, cb.BorrowedOn
) borrowed
on available.CarGroup = borrowed.CarGroup
where available.cnt = borrowed.cnt
顺便说一句,“Group”是列的错误名称,因为它是SQL保留字。我已将其重命名为CarGroup。
如果在同一天可以多次借用同一辆车,则将第二个子查询中的count(*)
更改为count(distinct cb.carId)
。
如果只需要一天,可以在WHERE子句中添加一个子句。
答案 1 :(得分:1)
首先,加入表格,这样我们就可以为每辆车借(一天)。
select c.id, c.GroupName, cb.day
from car c
left join (select * from CarBorrow where day = '23 Aug 2012') cb
on (c.id = cb.id)
所有未借用的汽车在当天都会有空。
在此之后,我们应该选择所有没有空值的组。 咆哮一个骗局:
select GroupName
FROM(
select c.id, c.GroupName, cb.day
from car c
left join (select * from CarBorrow where day = '23 Aug 2012') cb
on (c.id = cb.id)
)
group by GroupName
having count(day) = count(*)
(空的天数不计入COUNT)
答案 2 :(得分:1)
SELECT distinct(D1.CARGROUP)
FROM den_car d1
MINUS
(SELECT D.CARGROUP
FROM den_car d
WHERE d.id IN (SELECT c.ID
FROM den_car c
MINUS
SELECT b.id
FROM den_car_borrow b
WHERE B.DATE_BORROW = TO_DATE (SYSDATE)))
这可能是优化的但想法很简单:找到借来的,从所有汽车中减去它。然后找到重组。
希望它有所帮助。 (顺便说一下,还有很多其他方法可以做到。)
答案 3 :(得分:0)
我想我现在有一个解决方案:
select x.groupname from
(select a.groupname, count(*) as cnt from car a group by a.groupname) x
inner join
(
select b.groupname, count(*) as cnt from car b where b.carid in (select caraid from modavail where day ='23.08.2012')
group by b.groupname
) y
on x.groupname = y.groupname
where x.cnt = y.cnt and y.cnt ! = 0 ORDER BY GROUPNAME;
感谢您的帮助!!!!