SQL服务器选择
问题描述:
我有以下表命名tblMastTestElement
SQL服务器选择
cTestCode | cElementCode
24HCRECLE | CRE
CALCRECLE | CRE
CALEXR | CRE
CRE | CRE
CRECLE | CRE
EGFR | CRE
EGFR | EG
我需要一个查询返回EGFR为testcode具有的元素综合招聘考试及EG只
像这样
Select cTestCode
from tblMastTestElement
where cElementCode IN('CRE' And 'EG')
答
要返回cElementCode
的cTestCode 'CRE'和'EG'(不是或者)你可以使用。
SELECT cTestCode
FROM tblMastTestElement
WHERE cElementCode IN ('CRE', 'EG')
GROUP BY cTestCode
HAVING COUNT(DISTINCT cElementCode) = 2
答
这会奏效。
Select t1.cTestCode
from tblMastTestElement t1
where t1.cElementCode = 'CRE'
AND EXISTS (
Select 1
from tblMastTestElement t2
where t2.cElementCode = 'EG'
AND t1.cTestCode = t2.cTestCode)
)
答
Select distinct t1.cTestCode
from tblMastTestElement t1
join tblMastTestElement t2 on t2.cTestCode = t1.cTestCode
where t1.cElementCode = 'EG'
and t2.cElementCode = 'CRE'
答
这是远不及高效的马丁·史密斯的答案,但如果你坚持不工作,我们很可能会成为全面的解决方案:
SELECT cTestCode FROM tblMastTestElement WHERE cElementCode = 'CRE'
INTERSECT
SELECT cTestCode FROM tblMastTestElement WHERE cElementCode = 'EG'
如果没有按“T工作,运行此:
SELECT cTestCode, cElementCode
FROM tblMastTestElement
WHERE cTestCode = 'EGFR'
AND cElementCode IN ('CRE','EG');
如果是不返回两行,T如果你的数据不好。请注意,该查询不应该是答案,只是为了证明您的数据是否不正确。
这里的问题是你需要测试两个记录。您可以在每个表格的每个实例中测试每个元素的自加入 – jean