检查SQL查询中是否满足指定的所有条件

时间:2014-10-02 13:52:43

标签: sql sql-server

让我们假设我有以下派生表:

Comment | Condition_Lower_Score | Condition_Higher_Score | Question_Score
=========================================================================
text1   |          1            |            3           |       2
text1   |          3            |            5           |       4
text2   |          5            |            6           |       1
text2   |          3            |            6           |       4

我的表中有一条与条件有一对多关系的评论。每个条件都可以指定多个问题(在此表中,问题得分与不同的问题相关)。我需要创建一个只在满足所有条件时才选择注释的查询。

派生表是根据以下表格创建的:

注释:

Comment_ID | Comment_Text 
===========================
     1     |     text1
     2     |     text2

条件:

 Condition_ID | Condition_Lower_Score | Condition_Higher_Score |  Comment_ID | Question_ID
 =========================================================================================
      10      |          1            |             3          |      1      |     100
      11      |          3            |             5          |      1      |     101
      12      |          5            |             6          |      2      |     102
      13      |          3            |             6          |      2      |     103

问题:

Question_ID | Question_Score
============================
     100    |       2
     101    |       4
     102    |       1
     103    |       4     

所以在这种情况下,我希望只从派生表中选择'text1',而不是'text2',因为它的所有条件都不满足。

如何创建仅选择是否满足所有条件的查询?

2 个答案:

答案 0 :(得分:1)

WITH TestsCTE AS
(
SELECT M.Comment_Text AS Comment, 
       C.Condition_Lower_Score, 
       C.Condition_Higher_Score, 
       Q.Question_Score,
       CASE 
           WHEN Q.Question_Score BETWEEN C.Condition_Lower_Score AND C.Condition_Higher_Score
           THEN 1
       ELSE 0
       END AS Pass
FROM   [Condition] C
       JOIN Comment M
           ON C.Comment_ID = M.Comment_ID
       JOIN Question Q
           ON C.Question_ID = Q.Question_ID
)
SELECT COMMENT
FROM TestsCTE
GROUP BY COMMENT
HAVING MIN(Pass) = 1

<强> SQL FIDDLE DEMO

答案 1 :(得分:0)

select comment from (
    <query for your derived table here>
) t1 group by comment
having count(
   case 
   when question_score not between condition_lower_score and condition_higher_score 
   then 1 end
) = 0

select c.comment_text from comment c
join condition co on co.comment_id = c.comment_id
join question q on q.question_id = co.question_id
group by c.comment_text
having count(
   case 
   when question_score not between condition_lower_score and condition_higher_score 
   then 1 end
) = 0