在Postgres中按月和年编号排序

时间:2018-10-30 19:43:40

标签: postgresql

我有一个要在BI工具中使用的打击查询。

select
to_char(date_trunc('month', l.date_created)::date, 'Month YYYY') as "Month / Year",
  count(distinct l.lead_id) as "# New Leads"
  from leads l
  where l.date_created >= {{date_range_start}} and l.date_created <= {{date_range_end}}
  group by date_trunc('month', l.date_created)

分组工作正常,但是我无法弄清楚如何编写顺序以使结果按月和年的降序返回(按数字而不是按字母顺序排列的“一月与四月”)< / p>

1 个答案:

答案 0 :(得分:1)

SQL DEMO

select
  to_char(date_trunc('month', created)::date, 'Month YYYY') as "Month / Year",
  count(*) as "# New Leads"
from Table1  
group by date_trunc('month', created)
ORDER BY date_trunc('month', created) desc