关于group by的Oracle SQL查询

时间:2014-03-14 16:57:09

标签: sql oracle group-by

我有2个表,文章和看护人员,其中包含以下列和结构

SQL> desc caretaker;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 CID                                       NOT NULL NUMBER(5)
 CNAME                                              VARCHAR2(15)
 ADDRESS                                            VARCHAR2(20)
 SALARY                                             NUMBER(10,2)

SQL> desc article;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 ART_NO                                    NOT NULL NUMBER(5)
 ART_TITLE                                          VARCHAR2(15)
 TYPE                                               VARCHAR2(15)
 A_DATE                                             DATE
 CID                                                NUMBER(5)
 MUSEUM_ID                                          NUMBER(5)

我需要执行2个查询,

1)找到工资超过20000且照顾至少2篇文章的人所关心的文章的细节

2)显示照顾最大物品的看护人的详细信息。

对于第一个查询我已经做到了

select a.art_no,a.art_title,a.type,a.a_date from article a,caretaker c 
where a.cid = c.cid and c.salary > 20000;

现在我很困惑如何提取由照顾至少2篇文章的人提供的文章?!!

2)对于第二个查询,

select c.cid,c.cname,c.address,c.salary from caretaker c,article a 
where c.cid=a.cid 
    and count( select a.cid from article a group by a.cid ) = MAX(a.cid)?????
很困惑,请指正,谢谢 (我不应该加入命令)

1 个答案:

答案 0 :(得分:0)

对于第一个查询:

select a.art_no,a.art_title,a.type,a.a_date 
from article a,caretaker c
where a.cid = c.cid and c.salary > 20000
and c.cid in (select cid from article group by cid having count(cid) > 1)

SQL小提琴: http://sqlfiddle.com/#!4/bef24/16

对于第二个查询:

select cname, a.art_no,a.art_title,a.type,a.a_date 
from article a,caretaker c
where a.cid = c.cid and c.cid = (select cid 
                                 from(select cid, count(cid)
                                      from article
                                      group by cid
                                      having count(cid) = (select max(count(cid)) 
                                                     from article group by cid)));

SQL小提琴: http://sqlfiddle.com/#!4/bef24/18