2016-06-09 120 views
1

我有以下表命名tblMastTestElementSQL服务器选择

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') 
+0

这里的问题是你需要测试两个记录。您可以在每个表格的每个实例中测试每个元素的自加入 – jean

回答

4

要返回cElementCode的cTestCode 'CRE'和'EG'(不是或者)你可以使用。

SELECT cTestCode 
FROM tblMastTestElement 
WHERE cElementCode IN ('CRE', 'EG') 
GROUP BY cTestCode 
HAVING COUNT(DISTINCT cElementCode) = 2 
+0

没有行返回....感谢您试图帮助 – faiz

+2

@faiz - 是的。你必须采取我们的代码,而不是正确实施它。 http://sqlfiddle.com/#!9/edd335/3 –

+0

对不起马丁,是的,它回来了,非常感谢你为我节省了很多时间。昨晚我正在睡觉,这是在斯里兰卡的上午1点30分 – faiz

1

这会奏效。

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) 
) 
2
Select distinct t1.cTestCode 
from tblMastTestElement t1 
join tblMastTestElement t2 on t2.cTestCode = t1.cTestCode 
where t1.cElementCode = 'EG' 
and t2.cElementCode = 'CRE' 
+0

没有记录返回这个查询 – faiz

+0

@faiz - 应该有一次你用错误的cTestCode列修复错误。 http://sqlfiddle.com/#!9/edd335/2 –

+0

谢谢@MartinSmith。如果我有更多的空闲时间,我可以酸性测试我的和你的性能。你的答案是巧妙的;) – jean

1

这是远不及高效的马丁·史密斯的答案,但如果你坚持不工作,我们很可能会成为全面的解决方案:

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如果你的数据不好。请注意,该查询不应该是答案,只是为了证明您的数据是否不正确。