2014-10-02 36 views
1

满意让我们假设我有以下的派生表:检查指定的所有条件都在SQL查询

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'。

如何创建仅在满足所有条件时才选择的查询?

回答

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

+0

但如果是这种检查所有条件都满足的 '文本1'? – Emptypeace 2014-10-02 13:58:35

+0

有什么条件? JOIN语句应该处理这个。根据您的示例表,我的查询应返回您预期结果的前两行。 – 2014-10-02 14:01:33

+0

Condition_Lower_Score和Condition_Higher_Score。查看'text1'的问题分数是如何落入两个分数阈值范围内的。 – Emptypeace 2014-10-02 14:04:45

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