在写一个统计查询的 SQL 语句时,需要根据年、月、日分组,但要求返回的字段是日期格式:yyyy年MM月dd日。刚开始我的做法是返回年、月、日,然后再手动拼接年月日,而且还要判断月份和日期是否为个位数,是的话需要在左侧补零。项目经理看了我代码之后,告诉我直接可以在 SQL 中处理。下面是 SQL 语句:
SELECT CAST(stats_year AS character varying) || '年' || lpad(CAST(stats_month AS character varying), 2, '0') || '月' || lpad(CAST(stats_day AS character varying), 2, '0') || '日' AS statisticsTime,
SUM(stats_value) AS count, '周' AS mode
FROM t_cnitsec_attack_stats_hour
WHERE stats_name=#{statsName} AND stats_date BETWEEN (now() - INTERVAL '12 months') AND now()
GROUP BY statisticsTime