Sql查询返回符合条件的多行

时间:2014-04-17 02:07:53

标签: sql sql-server linq

我有一个调查系统,其中包含以下questionanswer

questionId personId response
1             a       red
2             a       blue
3             a       green
4             a       black
1             b       red
2             b       blue
3             b       green
4             b       black

我需要为搜索表单构建一个查询,允许用户选择问题和要返回的响应。即,用户可以选择question 1 answer = redquestion 3 and answer green

我必须返回符合该条件的personId个(在上表中它会返回a和b)

psuedo: select from questionanswer table all personId's where question=1 && answer=red AND those personId's where question=3 and answer was green

此代码将在管理员选择'搜索'之后运行。返回不同的a和b personId'

(看似简单但我必须遗漏一些东西?)

4 个答案:

答案 0 :(得分:1)

你如何传递QuestionIds和Responses?我们假设您最终将它们放入表变量中:

    DECLARE @Search TABLE 
    ( questionId int, 
      response varchar(30) ) 

然后你的SQL变为:

    SELECT q.personID
    FROM questionanswertable AS q
    INNER JOIN @Search AS s
    ON s.questionId = q.questionId
       AND s.response = q.response
    GROUP BY q.personID
    HAVING COUNT(1) = (SELECT COUNT(1) FROM @Search)

答案 1 :(得分:0)

SELECT DISTINCT personID
FROM questionanswertable 
WHERE (questionID = 1 AND response = 'red')
OR (questionID = 3 AND response = 'green')

答案 2 :(得分:0)

SELECT DISTINCT personID
FROM questionanswertable 
WHERE questionID = 3 AND response = 'green' AND personID in (
    SELECT DISTINCT personID
    FROM questionanswertable
    WHERE (questionID = 1 AND response = 'red'))

答案 3 :(得分:0)

SELECT DISTINCT personId
FROM questionanswer
WHERE questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 1 AND response = 'red')
AND questionId IN(SELECT questionId FROM questionanswer WHERE questionId = 3 AND response = 'green')