使用postgreSQL每月排序DDMMYYYY

时间:2017-09-25 13:17:06

标签: postgresql datetime

我正在使用PostgreSQL编写一个查询来计算某些内容但我想正确排序日期(DDMMYYYY)。

使用以下代码

WITH dis_id AS (SELECT 
DISTINCT ON (source_user_id) source_user_id,
  created_at
  FROM public.info_scammers )

SELECT  d.date, count(dis_id.source_user_id)
FROM (SELECT to_char(date_trunc('day',(current_date - offs)), 'DD-MM-YYYY') AS date
  FROM generate_series(0,365,1) AS offs
  ) d  LEFT OUTER JOIN
  dis_id
  ON (d.date = to_char(date_trunc('day',dis_id.created_at),'YYYY-MM-DD'))



GROUP BY d.date

结果是

Date        |   Count
01-01-2017  |   0

01-02-2017  |   0

01-03-2017  |   0

我想要的是

Date        |   Count
01-01-2017  |   0

02-01-2017  |   0

03-01-2017  |   0

我查了解现有的问题。但是大多数人都不使用PostgreSQL

谢谢

1 个答案:

答案 0 :(得分:0)

d.date保留为内部date中的SELECT类型(不要将其text转换为to_char),然后添加ORDER BY d.date并转换到外部text中的SELECT

类似的东西:

WITH dis_id AS (...)
SELECT to_char(d.date, 'DD-MM-YYYY'), count(...)
FROM (SELECT date_trunc(...) AS date
      FROM ...
     ) d
   LEFT OUTER JOIN ...
GROUP BY to_char(d.date, 'DD-MM-YYYY')
ORDER BY d.date;