我有两个表:Jobs
和JobItems
:
CREATE TABLE Jobs (
[JobId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY
);
Create TABLE JobItems(
[ItemId] UNIQUEIDENTIFIER NOT NULL,
[JobId] UNIQUEIDENTIFIER NOT NULL
);
并且对于Jobs
中的每一行,JobItems
中可以有一行,一行或多行,以使其JobId
与Jobs
中的行匹配,这意味着零,一个或多个“作业”包含该“项目”。
我需要从Jobs
中选择行,以便JobItems
中只有一行JobId
与Jobs
中的行匹配,并尝试来自{{3}的代码(稍微改动一下):
SELECT JobId, (SELECT Count(ItemId) from JobItems WHERE
JobItems.JobId=Jobs.JobId) from Jobs
问题是我现在需要以某种方式说我只需要一个匹配的行。所以我尝试为Count(ItemId)
SELECT JobId, (SELECT Count(ItemId) AS CountItemId from JobItems WHERE
JobItems.JobId=Jobs.JobId) from Jobs WHERE CountItemId=1
但这会让SQL服务器不满意 - 它说
列名
CountItemId
无效
如何只选择一个匹配的项目?
答案 0 :(得分:2)
基本的GROUP BY HAVING
子句会为你做..
SELECT Jobs.jobId
FROM Jobs
INNER JOIN JobItems
ON Jobs.JobId = JobItems.JobId
GROUP BY Jobs.jobId
HAVING COUNT(*)=1
答案 1 :(得分:1)
使用此查询:
SELECT JobId, Count(ItemId) from JobItems group by JobId;
答案 2 :(得分:1)
你可以这样做:
select *
from jobs i
where (select count(*) from jobitems ji where ji.jobid = j.jobid) = 1;
但是,如果表作业只包含所有作业ID而不包含任何其他内容,那么您根本不必从表作业中选择:
select jobid
from jobitems
group by jobid
having count(*) = 1;
答案 3 :(得分:1)
Select jobid
From jobitems
Group by jobid
Having count(*) = 1;
答案 4 :(得分:1)
您还可以创建临时结果集:
WITH T1 AS (
SELECT JobId
FROM Jobs
),
T2 AS (
SELECT JobId, Count(ItemId) AS CountItemId
FROM JobItems
GROUP BY JobID
)
SELECT JobId, CountItemId
FROM T2
WHERE CountItemId = 1