问题的SQL问题可能与和计数

时间:2019-02-12 14:38:17

标签: sql

我尝试过以下查询:为2个其他项目中的相同作业命名。但是结果却不是我所期望的。

我有这些表:

CREATE TABLE People (
    pid INT PRIMARY KEY,
    surname VARCHAR(127),
);
CREATE TABLE Work (
    idproject INT PRIMARY KEY,
    pid int FOREIGN KEY,
    job VARCHAR(127),
);

2 个答案:

答案 0 :(得分:1)

这些查询适用于2个相同的作业:

select p.surname, w.job
from People p
    join Work w on w.pid = p.pid
group by p.surname, w.job 
having count(1) = 2

如果您想知道大于或等于2,则必须将最后一个条件更改为:

select p.surname, w.job
from People p
    join Work w on w.pid = p.pid
group by p.surname, w.job 
having count(1) > 1

答案 1 :(得分:0)

此:

select w.* from work w
where exists (
  select 1 from work where job = w.job and pid = w.pid and idproject <> w.idproject
)

为您提供表work中包含1个pid和2个或更多不同项目中的相同job的所有行。
您可以将上面的查询加入到表People中:

select p.surname, w.job, w.idproject
from people p inner join  (
    select w.* from work w
    where exists (
      select 1 from work where job = w.job and pid = w.pid and idproject <> w.idproject
    )
) w 
on w.pid = p.pid
order by p.surname, w.job, w.idproject