2016-06-09 123 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如果你的數據不好。請注意,該查詢不應該是答案,只是爲了證明您的數據是否不正確。