1

我需要一条 SQL 语句来从数据库中提取那些同时具有附件标签的申请人。如果我想要具有 7 或 8 作为附件标签的申请人,但我需要同时具有这两个标签的申请人,那么下面的 q 语句可以正常工作。

select distinct(a.id) from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join ApplicantAttachment at on a.id = at.applicantid
where a.applicanttype = 'TCN/LN' and ad.groundlocation in (4,8,14) and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6 and at.tag in (7,8)

例如,从下面的集合中,我只想显示 ids 7332,7451 和 7449。

ID 标签
7328 8
7328 8
7332 8
7332 7
7337 7
7449 8
7449 7
7451 8
7453 7
7451 7

谢谢!

4

6 回答 6

7

你需要在下面做,而不是不同的:

GROUP BY a.id HAVING COUNT(a.id) = 2  
于 2012-04-23T18:05:27.583 回答
2

您可以加入 ApplicationAttachment 表两次以确保两个标签都存在。这样您就可以避免使用 DISTINCT 和 GROUP BY。

SELECT a.id
FROM applicant a
JOIN applicantdeployment ad ON a.id = ad.applicantid
JOIN ApplicantAttachment at7 ON a.id = at7.applicantid AND at7.tag = 7
JOIN ApplicantAttachment at8 ON a.id = at8.applicantid AND at8.tag = 8
WHERE a.applicanttype = 'TCN/LN' 
AND ad.groundlocation IN (4,8,14)
AND ad.deploymentstatus = 1
AND ad.trainingdeploymentstatus = 6
于 2012-04-23T18:16:55.923 回答
1

在您的示例数据中,不应该选择 7451 吗?您需要修改下面的代码以适合您的查询,但请尝试以下操作:

CREATE TABLE #Temp
(
    ID INT,
    Tag INT
)

INSERT INTO #Temp
(
    ID,
    Tag
)
SELECT 7328, 8 UNION
SELECT 7332, 8  UNION
SELECT 7332, 7  UNION
SELECT 7337, 7  UNION
SELECT 7449, 8  UNION
SELECT 7449, 7  UNION
SELECT 7451, 8  UNION
SELECT 7453, 7  UNION
SELECT 7451, 7

select distinct(ad.id) from #Temp ad
join #Temp at on ad.id = at.id
AND ad.Tag != at.Tag
where at.tag in (7,8)
AND ad.Tag IN (7, 8)
于 2012-04-23T18:09:46.667 回答
1

如果将 IN 列表项放入名为#Tags 的表中,这将起作用,并且如果标签数量发生变化,则无需重写查询。

select distinct(#Temp.ID)
from #Temp
where not exists (
  select * from #Tags
  where not exists (
    select * from #Temp as TempCopy
    where TempCopy.Tag = #Tags.Tag
    and TempCopy.ID = #Temp.ID
  )
)  

在英语中,这会选择那些没有缺少任何必需标签的 ID。

于 2012-04-23T19:00:40.857 回答
0

尝试:

select distinct(a.id)
from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join (select applicantid from applicantattachment at1
join applicantattachment at2 on at1.applicantid=at.applicantid
where at1.tag=7 and at2.tag=8) at
on a.id = at.applicantid
where a.applicanttype = 'TCN/LN'
and ad.groundlocation in (4,8,14)
and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6

将申请人附件表加入到自身中以仅获取相关的申请人ID。

于 2012-04-23T18:13:27.197 回答
-2
select distinct(a.id) from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join ApplicantAttachment at on a.id = at.applicantid
where a.applicanttype = 'TCN/LN' and ad.groundlocation in (4,8,14) and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6 and at.tag in (7,8) and a.id IN (7332,7449);
于 2012-04-23T18:06:43.337 回答