2012-02-16 152 views
0

Mysql group_concat我有一個我想要總結的不同屬性的表,然後將它們連接成一個JSON字符串,使它更容易通過網絡發送。這裏有一個簡單的表:Mysql group_concat與總和

t1 
type amount 
'atr1' 10 
'atr2' 10 
'atr1' 17 
'atr3' 20 
'atr3' 4 

我想是這樣

select concat('{', 
    group_concat(
     (select concat('"', type, '":', sum(amount)) from t1 group by type) 
    ), 
'}') 

,但失敗了。

我想'{"atr1":27,"atr2":10,"atr3":24}'

回答

1

嘗試此查詢落得 -

SELECT CONCAT('{', GROUP_CONCAT(c1), '}') FROM (
    SELECT CONCAT('"', type, '":', SUM(amount)) c1 FROM t1 GROUP BY type 
) t 
1

select 
    group_concat(concat('"', type, '":', TheSum)) 
FROM 
    (
    SELECT SUM(amount) AS TheSum,type 
    FROM t1 
    GROUP BY type 
    ) T