通过分组两列来计算记录

时间:2014-06-06 10:13:04

标签: mysql sql

我正在尝试计算每amountfk_id的变体数量。如果有多个变体,那么我希望返回记录,否则我希望忽略记录。

以下陈述有什么问题?

SELECT *, count(fk_id) AS `count` FROM table
WHERE count > 1
GROUP BY fk_id, amount;

表:

+-----------+----------+--------------+
| id        | fk_id    | amount       |
+-----------+----------+--------------+
|         1 | 100      | 5            |
|         2 | 200      | 10           |
|         3 | 200      | 10           |
|         4 | 200      | 10           |
|         5 | 200      | 15           |
+-----------+----------+--------------+

预期产出:

+-----------+----------+--------------+--------------+
| id        | fk_id    | amount       | count        |
+-----------+----------+--------------+--------------+
|         2 | 200      | 10           | 2            |
+-----------+----------+--------------+--------------+

1 个答案:

答案 0 :(得分:2)

您不能在WHERE子句中使用聚合函数。请改用HAVING子句:

SELECT MIN(id) as id,fk_id,amount, count(fk_id)-1 AS `count` 
FROM table
GROUP BY fk_id, amount
HAVING count(fk_id)>1

结果:

ID  FK_ID   AMOUNT  COUNT
2   200     10      2

请参阅SQL Fiddle中的结果。