这是我当前的查询:
SELECT SUM(round("records"."value")) AS sum_value,
to_char(service_date_time, 'Mon YYYY') AS to_char_service_date_time_mon_yyyy
FROM "records"
INNER JOIN "categories" ON "categories"."id" = "records"."category_id"
WHERE (value < 10000)
AND (categories.kind = 'Attendance')
AND (records.service_date_time >= '2013-01-01 00:00:00.000000'
AND records.service_date_time <= '2014-01-29 00:37:00.400862')
GROUP BY to_char_service_date_time_mon_yyyy
这将返回所有正确的数据:
3036710 Aug 2013
2792991 Jul 2013
3344243 Jun 2013
3121535 Apr 2013
3752803 Sep 2013
2931149 May 2013
3046820 Nov 2013
4437698 Mar 2013
2709170 Jan 2014
3709154 Jan 2013
3361630 Dec 2013
3008767 Oct 2013
3474820 Feb 2013
但是,我似乎无法通过新的日期格式列进行排序,因为它是一个字符串。如果我这样做,它将首先排序2013年4月,然后是2013年8月。我需要按月分类。我尝试了一些不同的东西,比如使用to_date而不是to_char,还尝试在排序前将列强制转换为日期。没有骰子。
有什么想法吗?
谢谢!
答案 0 :(得分:5)
我认为最简单的方法是:
order by min(service_date_time)
答案 1 :(得分:1)
您可以添加辅助列进行排序:
SELECT SUM(round("records"."value")) AS sum_value,
to_char(service_date_time, 'Mon YYYY') AS to_char_service_date_time_mon_yyyy,
max(to_char(service_date_time, 'yyyy-mm')) as yyyy_mm
FROM "records"
INNER JOIN "categories" ON "categories"."id" = "records"."category_id"
WHERE (value < 10000)
AND (categories.kind = 'Attendance')
AND (records.service_date_time >= '2013-01-01 00:00:00.000000'
AND records.service_date_time <= '2014-01-29 00:37:00.400862')
GROUP BY to_char_service_date_time_mon_yyyy
order by yyyy_mm
如果要删除辅助列,则:
SELECT sum_value, to_char_service_date_time_mon_yyyy
FROM (... copy the above query here...) t
答案 2 :(得分:0)
试试这个:
SELECT x.sum_value, x.to_char_service_date_time_mon_yyyy
FROM(
SELECT SUM(round("records"."value")) AS sum_value,
to_char(service_date_time, 'Mon YYYY') AS to_char_service_date_time_mon_yyyy,
to_char(service_date_time, 'Mon') AS month
FROM "records"
INNER JOIN "categories" ON "categories"."id" = "records"."category_id"
WHERE (value < 10000)
AND (categories.kind = 'Attendance')
AND (records.service_date_time >= '2013-01-01 00:00:00.000000'
AND records.service_date_time <= '2014-01-29 00:37:00.400862')
GROUP BY to_char_service_date_time_mon_yyyy
ORDER BY month) x
我们的想法是使用月份获取另一列并按其排序,您可以在子查询中执行此操作,以避免在结果集上选择新列month
。