如何找出重复项并在另一个表中计算它们

时间:2013-08-16 05:49:23

标签: sql sqlite

我有一个类似于结果的sqlite表,并希望通过计算选项的数量来创建类似finalResults的表。我正在使用sqlite

   Table Name: Results           Table Name: finalResults
   ___________ _________         __________  _______  ________  _______  _______
    questionId| optionId         questionId| option1 | option2 |option3 |option4
    --------------------         -----------------------------------------------    
       40     | 3                40        | 1       |  2      | 4     | 1
       40     | 3                41        | 2       |  1      | 1      | 3
       40     | 2
       40     | 4
       40     | 2
       40     | 1
       40     | 3
       40     | 3
       41     | 1
       41     | 3
       41     | 2
       41     | 4
       41     | 4
       41     | 4
       41     | 1

谢谢

2 个答案:

答案 0 :(得分:2)

你可以这样做

INSERT INTO finalResults(questionId, option1, option2, option3, option4)
SELECT questionId,
       MIN(CASE WHEN optionid = 1 THEN n END) option1,
       MIN(CASE WHEN optionid = 2 THEN n END) option2,
       MIN(CASE WHEN optionid = 3 THEN n END) option3,
       MIN(CASE WHEN optionid = 4 THEN n END) option4
  FROM
(
  SELECT questionId, optionid, COUNT(*) n
    FROM results
   GROUP BY questionId, optionid
) q
 GROUP BY questionId

这是 SQLFiddle 演示

INSERT INTO finalResults(questionId, option1, option2, option3, option4)
SELECT questionId,
       SUM(CASE WHEN optionid = 1 THEN 1 ELSE 0 END) option1,
       SUM(CASE WHEN optionid = 2 THEN 1 ELSE 0 END) option2,
       SUM(CASE WHEN optionid = 3 THEN 1 ELSE 0 END) option3,
       SUM(CASE WHEN optionid = 4 THEN 1 ELSE 0 END) option4
  FROM results 
 GROUP BY questionId

这是 SQLFiddle 演示

两种情况下的输出:

| questionId | option1 | option2 | option3 | option4 |
------------------------------------------------------
|         40 |       1 |       2 |       4 |       1 |
|         41 |       2 |       1 |       1 |       3 |

答案 1 :(得分:0)

尝试以下查询

select questionId,
sum(optionId==1) as option1,
sum(optionId==2) as option2,
sum(optionId==3) as option3
from results
group by questionId

或sqlfiddle http://sqlfiddle.com/#!7/415b7/6(打开Chrome& safari)