我正在尝试以下列格式获取SQL结果:
+------------+--------------+
| regions| quarter_values|
+------------+--------------+
| A | 0,2,0,2 |
| B | 1,3,4,5 |
| C | 2,6,2,0 |
+------------+--------------+
但是通过以下查询,它会提供 Error Code: 1111. Invalid use of group function
SELECT r.regions,
group_concat(
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 1 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 2 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 3 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 4 THEN 1 ELSE 0 END) ) as 'quarter_values'
FROM requests r group by r.regions;
有关此查询的任何帮助吗?
答案 0 :(得分:1)
您无法嵌套聚合函数。
但是你不需要使用GROUP_CONCAT
,只需要普通的连接。
SELECT regions,
CONCAT_WS(',',
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 1 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 2 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 3 THEN 1 ELSE 0 END) ,
sum( CASE WHEN r.request_type="create" and quarter(created_at)= 4 THEN 1 ELSE 0 END)
) as quarter_values
FROM requests r
group by r.regions;