2016-01-18 55 views
2

我的表看起來像這樣:mysql:如何從一箇中提取多個表並在每個中分組,然後合併爲一個結果?

+------+------+------+ 
| prov | amnt | type | 
+------+------+------+ 
| on | 10 | 1 | 
| on | 10 | 1 | 
| on | 12 | 2 | 
| ab | 10 | 1 | 
| ab | 12 | 2 | 
| ab | 12 | 2 | 
| qc | 12 | 2 | 
| qc | 13 | 3 | 
| qc | 13 | 3 | 
+------+------+------+ 

我想返回一個表,其中,每個提供圖片有按類型,每個類型的總和和計數,像這樣分組摘要:

+------+-------+------+------+ 
| prov | total | type | count| 
+------+-------+------+------+ 
| on | 20 | 1 |  2| 
| on | 12 | 2 |  2| 
| ab | 10 | 1 |  1| 
| ab | 24 | 2 |  2| 
| qc | 12 | 2 |  1| 
| qc | 26 | 3 |  2| 
+------+-------+------+------+ 

基本上,如果我爲每個省進行三次手動輸入查詢,我將通過三個不同的查詢獲得三個不同表中的數據。

SELECT prov, SUM(fine) AS total, code, COUNT(code) AS COUNT 
FROM table 
WHERE prov = 'on' 
GROUP BY code; 

    +------+-------+------+------+ 
    | prov | total | type | count| 
    +------+-------+------+------+ 
    | on | 20 | 1 |  2| 
    | on | 12 | 2 |  2| 
    +------+-------+------+------+ 

回答

0

添加provgroup by

SELECT prov, SUM(fine) AS total, code, COUNT(code) AS COUNT 
FROM table 
GROUP BY prov, code; 
0

也許你可以使用一個SQL合計,如:

SELECT *, COUNT(*) FROM tablename GROUP BY prov, type; 

有關組按功能的詳細信息:see here

0

您可以通過省和類型需要組。以下是你需要什麼:

select  
`prov`, sum(`amnt`) as `total`, count(*) as `count`, `type` 
group by `prov`, `type`; 
0

改變您的查詢是:

SELECT prov, SUM(amnt) AS total, type, COUNT(type) AS COUNT 
FROM table 
GROUP BY prov, code; 
相關問題