一、数据库的格式如下: 可以看出fix_time日期格式是:yyyy-MM-dd的格式,但是我只需要根据年月格式去查询。
首先根据fix_time时间分组,然后使用DATE_FORMAT() 函数用于以不同的格式显示日期/时间数据。 代码如下: <select id="last12MonthsList" resultMap="BaseResultMap" parameterType="java.util.List" > select COUNT(*), DATE_FORMAT(fix_time, '%Y-%m') as fix_time from cars where unit_id IN <foreach collection="unitIdList" item="unitIdList" open="(" separator="," close=")"> #{unitIdList} </foreach> AND DATE_FORMAT(fix_time, '%Y-%m') IN <foreach collection="list" item="list" open="(" separator="," close=")"> #{list} </foreach> GROUP BY DATE_FORMAT(fix_time, '%Y-%m') </select>
单独在mysql中查询写法如下:
select fix_time, COUNT(*) from cars where DATE_FORMAT(fix_time,'%Y-%m') = '2019-03'
运行结果如下: