SELECT SQL Server中的条件计算

时间:2015-12-20 06:49:51

标签: sql sql-server

我有如下的Question_Data表:

------------------------------
QuestionID | Attempts | Wrong
------------------------------
     1     |   20     |   7
     2     |   1      |   4
     3     |   14     |   2
     4     |   30     |   5

当收到请求时,我处理它并产生一个名为"响应表"的表。 (样本回应表)

---------------------
QuestionID | Response
---------------------
     1     |   T
     2     |   F
     3     |   F
     4     |   F
     5     |   T

现在我想要的是我想更新" Question_Data"表格基于"回应"表格如下: 新的" Question_Data"表:

------------------------------
QuestionID | Attempts | Wrong
------------------------------
     1     |   21     |   7
     2     |   2      |   5
     3     |   15     |   3
     4     |   31     |   6
     5     |   1      |   0

我在" Question_Data"中检查了QuestionID。表格,如果它存在于" Question_Data"我把它增加了#34;尝试"如果回应是" F"增量"错误"。

但是如果问题ID不存在于" Question_Data"表。插入一个具有相同QuestionID的新行并增加其" Attempts"到1并且如果响应是" T"将错误设为0。

我是SQL新手。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

UPDATE  Q
SET     Q.Attempts = Q.Attempts + 1 ,
        Q.Wrong = Q.Wrong + ( CASE WHEN R.Response = 'F' THEN 1
                                   ELSE 0
                              END )
FROM    Question_Data Q
        INNER JOIN Responses_Table R ON Q.QuestionID = R.QuestionID 

更新后如果Question_Data中没有数据运行此查询

INSERT INTO Question_Data
        (QuestionID ,
          Attempts ,
          Wrong)
    SELECT  
        R.QuestionID ,
        1,
        (CASE WHEN R.Response = 'F' THEN 1
              ELSE 0
         END) Wrong
    FROM    
        Responses_Table R
    LEFT JOIN 
        Question_Data Q ON Q.QuestionID = R.QuestionID
    WHERE   
        Q.QuestionID IS NULL

答案 1 :(得分:0)

假设QuestionIDQuestions_Data表中的Responses都是唯一的,您可以使用update-join语法:

UPDATE qd
SET    Attempts = Attempts + 1,
       Wrong = Wrong + CASE Response WHEN 'F' THEN 1 ELSE 0 END
FROM   Questions_Data qd
JOIN   Reponse r ON qd.QuestionID = r.QuestionID