如何按月份倒序排序考勤日期?(1月置底,12月置顶)
解决方案:按月份逆序(12月→1月)排序考勤记录
要实现12月排在最顶部、1月排在最底部的排序需求,我们需要基于日期的月份数字逆序来排序,同时保留同月份内原有的日期排序逻辑。
核心思路
- 提取日期的月份数字(比如12月对应12,1月对应1),按这个数字降序排列,就能实现12月在前、1月在后的效果
- 同月份内,保持你原本的日期排序逻辑(比如按日期从新到旧/从旧到新排列)
修改后的SQL查询语句
select distinct (select ARRAY_TO_STRING(ARRAY_AGG(ARRAY[to_char(t1.l_time,'HH12:mi AM')]::text), ',') from (select (al1.create_time AT TIME ZONE 'UTC+5:30')::time as l_time from users.access_log as al1 where al1.user_id = al.user_id and al1.login_status = 1 and al1.create_time::date = al.create_time::date order by al1.create_time::time ASC ) as t1 ) as login_time, (select ARRAY_TO_STRING(ARRAY_AGG(ARRAY[to_char(t2.o_time,'HH:mi AM')]::text), ',') from (select (al2.create_time AT TIME ZONE 'UTC+5:30')::time as o_time from users.access_log as al2 where al2.user_id = al.user_id and al2.login_status = 0 and al2.create_time::date = al.create_time::date order by al2.create_time::time ASC ) as t2 ) as logout_time, al.create_time::date from users.access_log as al where al.user_id = ? -- 新增排序逻辑,实现月份逆序+同月份日期排序 order by EXTRACT(MONTH FROM al.create_time) DESC, -- 按月份数字降序,12月在前、1月在后 al.create_time::date DESC; -- 同月份内按日期从新到旧排列,需从旧到新可改为ASC
关键说明
EXTRACT(MONTH FROM al.create_time):从日期中提取1-12的月份数字值,按这个值降序排序是实现需求的核心——直接按月份名称排序会遵循字母顺序(比如"Apr"会排在"Dec"前面),不符合我们要的12到1的顺序。- 同月份内排序:第二个排序条件可以根据你的原有需求调整,示例中用
DESC保持同月份内日期从新到旧排列,若你原本是按旧到新排序,改成ASC即可。 - 如果需要在结果中显示月份名称(比如"Dec"、"Feb"),可以在SELECT列表中添加
to_char(al.create_time, 'Mon') as month_name,但排序逻辑仍需依赖月份数字。
内容的提问来源于stack exchange,提问作者user8823283
相关产品推荐
相关产品推荐

