我正在使用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
谢谢
答案 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;