group by基于mySql中列值的一部分

时间:2015-01-26 06:17:26

标签: mysql sql database

我有一个mySql表调用详细信息。详细信息表具有列调用日期,其日期类似于2015-02-01。从同一个日期可以有多行。

我想查找一年中每个月包含的行数COUNT()

例如,

'568', '192.168.1.100', '790', '1.00', '2014-11-14'    
'569', '192.168.1.100', '780', '1.00', '2014-11-14'  
'699', '192.168.1.100', '780', '1.00', '2014-11-16'
'767', '192.168.1.102', '780', '1.00', '2014-12-15'   
'768', '192.168.1.102', '780', '1.00', '2014-12-15'

这应该给COUNT像:

 '2014-11-' as 3
 '2014-12-' as 2

如何使用sql select查询执行此操作。

2 个答案:

答案 0 :(得分:3)

Select DATE_FORMAT(My_Call_Date_Field, '%Y-%m') as MyYearAndMonth, Count(*) as MyCount
From My_Call_Details_Table Group By  DATE_FORMAT(My_Call_Date_Field, '%Y-%m')

您也可以使用CAST function of MySql

Select substr(convert(My_Call_Date_Field, CHAR), 1, 7) as MyYearAndMonth, Count(*) From My_Call_Details_Table Group By substr(convert(My_Call_Date_Field, CHAR), 1, 7) Order By substr(convert(My_Call_Date_Field, CHAR), 1, 7) 

回应特定于您案件的其他信息,如您对Ed King先前回答的评论中所示:此处为:

 SELECT DATE_FORMAT(detailtable.date, '%Y-%m') , AVG(detailtable.loadstate) as "load",count(detailtable.loadstate) as "count" from ruby_snmp.detailtable where ipaddtress='192.168.1.102' and date LIKE '2014-12-%' GROUP BY DATE_FORMAT(detailtable.date, '%Y-%m')

答案 1 :(得分:1)

使用mysql函数,分组和计数转换为月份和年份:

SELECT month(calldate) as m, year(calldate) as y, count(*) 
FROM calldetails 
GROUP by m, y;

鉴于附加信息,我将采取以下措施:

SELECT YEAR(detailtable.date) as y,
    MONTH(detailtable.date) as m, 
    AVG(detailtable.loadstate) as "load",
    count(detailtable.loadstate) as "count" 
FROM ruby_snmp.detailtable 
WHERE ipaddtress='192.168.1.102' and date LIKE '2014-12-%' 
GROUP BY y, m;

格式变量y和m将被忽略,但需要在那里才能使该组工作。您可以添加FORMAT函数以提供第二篇文章中提到的特定YYYY-MM,或者您可以在程序/报告编写器中处理数据表示。