PL / SQL语句的SQL查询无效

时间:2017-04-23 23:47:09

标签: sql oracle

我正在尝试执行一条SQL语句,我计划将其与PL / SQL游标一起使用。如果他们正在处理多个项目,它将获取员工姓名和他们正在处理的项目。出于某种原因,“有计数(pno)> 1”规定在这里不起作用。它只是说“没有找到数据”

我有什么问题吗?我在查询下面包含了我的数据库代码。

查询:

select pname, fname
from project, works_on, employee
where pno=pnumber and essn=ssn
group by pname, fname
having count(pno)>1;

Works_on表:

create table works_on (
Essn    char(9) not null,
Pno int not null,
hours   decimal(3,1),
primary key(essn, pno),
foreign key(Essn) references employee,
foreign key(pno) references project);

项目表:

create table project (
Pname varchar2(15) not null,
Pnumber int     not null,
Plocation varchar2(15),
Dnum    int not null,
primary key (Pnumber),
unique (Pname),
foreign key(Dnum) references department(Dnumber));

员工表:

 create table employee (
 Fname  varchar2(15) not null,
 Minit  char(1),
 Lname  varchar2(15) not null,
 Ssn    char(9),
 Bdate  date,
 Address    varchar2(30),
 Sex    char(1),
 Salary decimal(10,2),
 super_ssn  char(9),
 dno    int,
 primary key (Ssn),
 foreign key (dno) references department(Dnumber));

修改

我设法做了这项工作:

select fname, pname
  from employee, works_on, project
  where essn=ssn and pno=pnumber
  group by fname, pname
  having count(pnumber) > 1

是什么让pnumber取代pno?

1 个答案:

答案 0 :(得分:1)

  

我的预期输出是员工名字和项目名称的列表,其中员工正在处理多个项目。

这样的事情:

SELECT e.fname, p.projects
FROM   (
  SELECT w.essn,
         LISTAGG( p.pname, ',' ) WITHIN GROUP ( ORDER BY p.pname ) AS projects
  FROM   works_on w
         INNER JOIN
         project p
         ON ( w.pno = p.pnumber )
  GROUP BY w.essn
  HAVING COUNT( DISTINCT w.pno ) > 1
) p
INNER JOIN
employee e
ON ( p.essn = e.ssn )

或:

SELECT e.fname,
       p.pname
FROM   (
         SELECT w.*,
                COUNT( pno ) OVER ( PARTITION BY essn ) AS num_projects
         FROM   works_on w
       ) w
       INNER JOIN
       employee e
       ON ( e.ssn = w.essn )
       INNER JOIN
       project p
       ON ( w.pno = p.pnumber )
WHERE  w.num_projects > 1