id idtest result
1 1 2
1 2 1
1 3 2
2 1 2
2 2 1
2 3 1
3 1 1
3 2 2
3 3 1
希望获得具有与条件匹配的相同ID的所有行。 例如:获取具有相同id的所有行(idTest = 2和result = 1)和(idTest = 3且result = 2)
结果:
id idtest result
1 1 2
1 2 1
1 3 2
查询是什么? 谢谢!
答案 0 :(得分:1)
你是说这个吗?
SELECT * FROM table WHERE id = 1 and (result = 1 OR result = 2)
他的:
SELECT *
FROM table WHERE (idTest = 2 OR idTest = 3) AND (result=1 OR result=2)
答案 1 :(得分:0)
ID test res
1 1 2
1 2 1
1 3 2
2 1 1
2 2 2
2 3 2
3 1 1
3 2 2
3 3 1
对不起。这将是我的表。并希望获得具有与条件匹配的相同ID的所有行。例如:获取具有相同id的所有行(test = 2和res = 1)和(test = 3且res = 2)
结果:
ID test res
1 1 2
1 2 1
1 3 2
为了获得三行,查询是什么?谢谢!
答案 2 :(得分:0)
您似乎希望id的所有行都包含具有该特定组合的行。怎么样:
with ids as (
select id
from mytable
where (idTest=2 and result=1) or (idTest=3 and result=2)
group by id
having count(id) = 2
)
select mytable.* from mytable
inner join ids
on ids.id = mytable.id
这将获取两个条件适用的id列表,然后获取这些id的所有行。
答案 3 :(得分:0)
您可以使用EXISTS
:
SELECT id, idTest, result
FROM dbo.TableName t
WHERE EXISTS
(
SELECT 1 FROM dbo.TableName t2
WHERE t.id = t2.id
AND(
( t2.idTest=2 AND t2.result=1 )
OR
( t2.idTest=3 AND t2.result=2 )
)
)
更新:结果不同:
id idTest result
1 1 2
1 2 1 <-- satisfies your condition
1 3 2 <-- satisfies your condition
2 1 2
2 2 1 <-- satisfies your condition
2 3 1
因此,我的理解不正确或您的预期结果。我还有ID = 2,因为第二个id-2行符合条件。
答案 4 :(得分:0)
SELECT *
FROM table t1
WHERE EXISTS (SELECT 1 FROM table WHERE id = t1.id AND idtest = 2 AND result = 1)
AND EXISTS (SELECT 1 FROM table WHERE id = t1.id AND idtest = 3 AND result = 2)
如果您需要更多
,请继续添加更多AND EXISTS
或者如果对你更有意义,你可以使用IN
SELECT *
FROM table
WHERE id IN (SELECT id from table where idtest = 2 and result = 1)
AND id IN (SELECT id from table where idtest = 3 and result = 2)
答案 5 :(得分:0)
你是否需要一种以通用方式处理条件的方法,比如它们是否在另一个表中的值?或者你只需要一种方法来拉出两个独立条件的结果?
如果是后者,那么这应该有效:
SELECT
id
FROM
(SELECT id
FROM tbl
WHERE idTest=2 AND RESULT=1) cond1 INNER JOIN
(SELECT id
FROM tbl
WHERE idTest=3 AND RESULT=2) cond2 ON
cond1.id = cond2.id
否则,如果您的条件是通用的并存储在表格中,您需要以下内容:
SELECT
id
FROM
(SELECT id
FROM tbl FULL OUTER JOIN conditions c
WHERE c.isUseMe = 1 AND c.SEQ = 1 AND idTest=c.idTestVal AND result=c.resultVal) cond1 INNER JOIN
(SELECT id
FROM tbl FULL OUTER JOIN conditions c
WHERE c.isUseMe = 1 AND c.SEQ = 2 AND idTest=c.idTestVal AND result=c.resultVal) cond2 ON
cond1.id = cond2.id
如果将4个值作为参数传入,则需要类似以下内容:
SELECT
id
FROM
(SELECT id
FROM tbl
WHERE idTest=@idTestVal1 AND result=@resultVal1) cond1 INNER JOIN
(SELECT id
FROM tbl
WHERE idTest=@idTestVal2 AND result=@resultVal2) cond2 ON
cond1.id = cond2.id