2016-12-18 203 views
0

我希望根據條件擴展一個簡單的「GROUP/COUNT BY」查詢,條件是隻需要一定數量的行。MYSQL GROUP BY/COUNT條件

這是一張簡單的表格。一個正常的「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  | 
+----------+---------+ 
+0

更新您的文章。此外,你得到的錯誤。 – nyedidikeke

+0

爲什麼不等待5?我錯過了什麼;你正在尋找未刪除的條目? – Zack

回答

0

我想知道你爲什麼要做查詢,如果你事先知道所有需要的行。 無論如何,一個單一的條件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 
0

與您的查詢,SQL的創建和插入試試這個:::

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