Oracle SQLPlus列出值为'有'来自多个表

时间:2014-12-10 05:59:23

标签: sql oracle

Goodevening,溢出者!

我正在尝试显示已签出多个book_copy的教师客户的CID,以及check_copies签出的数量。我必须使用HAVING语句。教师是CUSTOMER表属性“CATEGORY”下的三种类型之一。我尝试了一些不同的东西,但现在我就是这样:

Select OUT_TO_CID "CID", count(COPY_NUM) "Books checked out" from BOOK_COPY
group by OUT_TO_CID having count(COPY_NUM) > 1;

这段代码有效,并且允许我以正确的方式向所有客户展示多个book_copy签出 - 不幸的是,我应该只为教职员工展示它。但是我如何从这里到达那里?嵌套子查询是解决方案吗?

好的,所以我现在尝试使用嵌套的子查询,但我很确定我做错了......:D我现在在从子开始的子查询行中出现错误。

Select OUT_TO_CID "CID",
count(COPY_NUM) "Books checked out"
from BOOK_COPY
group by OUT_TO_CID
having count(COPY_NUM) > 1
in (select CID from CUSTOMER where CATEGORY = 'Faculty')
;

这些是有问题的表格:

create table BOOK_COPY
(Copy_Num number(5),
Bookid  number(5),
out_to_CID number(6),
Date_Out date,
Date_Due date,
Held_Until date,
held_for_CID number(6),
CONSTRAINT PKCOPY PRIMARY KEY (Copy_Num,Bookid),
CONSTRAINT FKCID FOREIGN KEY (out_to_CID) references CUSTOMER (CID),
CONSTRAINT FKHeld FOREIGN KEY (held_for_CID) references CUSTOMER (CID),
CONSTRAINT FKBookid FOREIGN KEY (Bookid) references BOOK (Bookid));

create table CUSTOMER
(CID number(6),
First_Name varchar2(12),
Last_Name varchar2(12),
Category varchar2(7),
Balance_Due number(4,2),
SponsorID number(6),
CONSTRAINT pkCID PRIMARY KEY (CID),
CONSTRAINT fkCUSTOMER foreign key (sponsorID) references customer);

如果我的帖子有些违反规定,请告诉我。并感谢阅读它到最后; - )

1 个答案:

答案 0 :(得分:3)

您已经到了一半,因为您了解必须加入2个表才能按类别过滤。因此,这就是我们要做的:

Select b.OUT_TO_CID "CID",
count(b.COPY_NUM) "Books checked out"
from BOOK_COPY b
inner join CUSTOMER c on b.out_to_cid = c.cid
where c.category = 'Faculty'
group by b.OUT_TO_CID
having count(b.COPY_NUM) > 1