mysql如何按日和月查询数据库表并生成总计

时间:2013-12-25 09:45:58

标签: mysql sql select group-by sum

我有以下数据库表

"id","date_occurred","country","town","quantity"
"1","2012-06-01","England","Andover","82"
"2","2012-06-01","England","Colchester","569"
"3","2012-06-01","England","Farnham","1"
"4","2012-06-01","England","England","4"
"5","2012-06-01","England","America","13"
"6","2012-06-01","America","England","114"
"7","2012-06-02","England","Andover","4"
"8","2012-06-02","England","Colchester","207"
"9","2012-06-02","America","England","14"
"10","2012-06-03","England","Andover","3"
"11","2012-06-03","England","Colchester","72"
"12","2012-06-03","England","America","1"
"13","2012-06-03","America","England","15"
"14","2012-07-04","England","Andover","1"
"15","2012-07-04","England","Colchester","309"
"16","2012-07-04","England","America","4"
"17","2012-07-04","America","England","11"
"18","2012-08-05","England","Andover","2"
"19","2012-08-05","England","Colchester","319"
"20","2012-08-05","England","Farnham","1"
"21","2012-08-05","England","America","4"
"22","2012-08-05","America","England","25"
"23","2012-08-06","England","Andover","93"
"24","2013-06-06","England","Colchester","542"
"25","2013-06-06","England","Farnham","1"
"26","2013-06-06","England","England","4"
"27","2013-06-06","England","America","7"
"28","2013-06-06","America","England","115"

我想从查询中生成以下输出

特定月份每个国家/地区的每日总销售额

2012-06-01 England 669
2012-06-01 America 114
2012-06-02 England 211 

特定月份每个城镇的每日总销售额

2012-06-01 Andover 82
2012-06-02 Andover 4

我一直在尝试使用group by,sum和count进行各种查询,但无法获得正确的输出。

任何简单的解决方案或指导欢迎。提前致谢

1 个答案:

答案 0 :(得分:1)

试试这个:

特定月份每个国家/地区的每日总销售额:

SELECT date_occurred, country, SUM(quantity)
FROM tableA 
WHERE YEAR(date_occurred) = 2013 AND MONTH(date_occurred) = 6
GROUP BY date_occurred, country

特定月份每个城镇的每日总销售额:

SELECT date_occurred, town, SUM(quantity)
FROM tableA 
WHERE YEAR(date_occurred) = 2013 AND MONTH(date_occurred) = 6
GROUP BY date_occurred, town