group by子句不产生预期的总和

时间:2013-12-24 10:35:55

标签: sql sqlite select group-by sum

我正在开发iPhone应用程序并使用sqlite数据库。

我有answer_ELA表如下:

Id    | observation_id    | question_no    | answer    | answer2
-------------------------------------------------------------------
1     | 60                | 0              | 2         | 1
2     | 60                | 1              | 3         | 4
3     | 61                | 0              | 3         | 4
4     | 61                | 1              | 3         | 2
5     | 62                | 0              | 3         | 1
6     | 62                | 1              | 1         | 2

我想要结果

question_no    | total
-------------------------
0              | 14
1              | 15

但它的给予

question_no    | total
-------------------------
0              | 4
1              | 3

最后观察的手段_id仅为62

查询如下:

SELECT 
    question_no,
    (answer+answer2) total
FROM 
    answers_ELA 
WHERE
    observation_id IN(60,61,62) 
GROUP BY 
    question_no

这有什么问题,我该怎么办才能得到理想的结果。

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT question_no, SUM(answer+answer2) total
FROM answers_ELA 
WHERE observation_id IN (60,61,62) 
GROUP BY question_no

答案 1 :(得分:1)

您没有分配聚合功能。尝试SUM(回答+回答2)。

答案 2 :(得分:0)

猜猜看,这个会对你有用......

SELECT question_no, 
       Sum(answer + answer2) total 
FROM   answers_ela 
WHERE  observation_id IN( 60, 61, 62 ) 
GROUP  BY question_no
ORDER  BY question_no;