累积总计的MySQL子查询语法错误

时间:2013-12-27 11:56:26

标签: mysql

我有一张表格如下:

test_id | id | option | visits
------------------------------
1       | 1  | a      | 7
1       | 2  | b      | 12
1       | 3  | a      | 2
1       | 4  | b      | 4

我需要获得选项'a'和选项'b'的累计访问量。

我的查询如下:

SELECT *,
    ( SUM(visits) WHERE `option` = 'a' ) as visitsA, 
    ( SUM(visits) WHERE `option` = 'b' ) as visitsB
    FROM `table`
    WHERE test_id = 1

我收到以下错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `option` = 'a' ) as visitsA, ( SUM(visits) WHERE `option` = 'b' ' at line 2

1 个答案:

答案 0 :(得分:3)

你做错了。 SUM()中不允许使用“WHERE”。相反,做:

SELECT *,
    SUM(IF(`option`='a', visits, 0)) as visitsA, 
    SUM(IF(`option`='b', visits, 0)) as visitsB
FROM `table`
WHERE test_id = 1