具有条件

时间:2016-12-18 23:06:06

标签: mysql

我希望根据条件扩展一个简单的'GROUP / COUNT BY'查询,其条件只需要一定数量的行。

这是一张简单的表格。普通的“GROUP BY”会计算并返回完整的行数,但我需要使用表格旁边的语句扩展我的查询:

+-----+----------+----------+-------+
| id  | deleted  | status   |  ref  |
+-----+----------+----------+-------+
|   1 |        0 | paid     | 10001 |
|   2 |        0 | paid     | 10001 |
|   3 |        0 | paid     | 10001 |   WHERE status = paid ABD id IN (2,3) //COUNT = 2
|   4 |        0 | paid     | 10002 |
|   5 |        1 | cat      | 10002 |
|   6 |        1 | cat      | 10002 |   WHERE status = cat AND id IN (6) //COUNT = 1
|   7 |        0 | cat      | 10003 |
|  12 |        0 | pending  | 10004 |
|  13 |        1 | pending  | 10005 |
|  14 |        1 | pending  | 10005 |
|  15 |        1 | pending  | 10005 |   WHERE status = pending AND id IN(12,14,17) COUNT = 3
|  16 |        0 | pending  | 10005 |
|  17 |        0 | pending  | 10006 |
|  18 |        0 | pending  | 10006 |
|  19 |        0 | pending  | 10006 |
+-----+----------+----------+-------+

在上面列出的条件下,获得所需结果的最简单方法是什么?

+----------+---------+
| status   |  COUNT  |
+----------+---------+
| paid     | 2       |
| cat      | 1       |
| pending  | 3       | 
+----------+---------+

2 个答案:

答案 0 :(得分:0)

如果您事先知道所有需要的行,我想知道为什么要进行查询。 无论如何,单个where-condition where id IN (2,3,6,12,14,17)应该完成这项工作。所以最后的查询是

select status, count(*)
from mySimpleTable
where id IN (2,3,6,12,14,17)
group by status

答案 1 :(得分:0)

试试这个:::

select status, count(*) as 'count'
from myTable
where (id IN (2,3) AND status= 'paid') OR
(status = 'cat' AND id IN (6)) OR
(status = 'pending' AND id IN(12,14,17))
group by status