从数据库中获取每月统计信息的优雅方式(没有动态 SQL)?

Elegant way to get per month Stats from DB (without dynamic SQL)?

考虑获取每月的订单数量。我目前有这个:

select
  (select count(*) from orders o where o.created_at >= '2017-01-01' and o.created_at < '2017-02-01') as "Jan",
  (select count(*) from orders o where o.created_at >= '2017-02-01' and o.created_at < '2017-03-01') as "Feb",
  (select count(*) from orders o where o.created_at >= '2017-03-01' and o.created_at < '2017-04-01') as "Mar",
  (select count(*) from orders o where o.created_at >= '2017-04-01' and o.created_at < '2017-05-01') as "Apr",
  (select count(*) from orders o where o.created_at >= '2017-05-01' and o.created_at < '2017-06-01') as "May",
  (select count(*) from orders o where o.created_at >= '2017-06-01' and o.created_at < '2017-07-01') as "Jun",
  (select count(*) from orders o where o.created_at >= '2017-07-01' and o.created_at < '2017-08-01') as "Jul",
  (select count(*) from orders o where o.created_at >= '2017-08-01' and o.created_at < '2017-09-01') as "Aug",
  (select count(*) from orders o where o.created_at >= '2017-09-01' and o.created_at < '2017-10-01') as "Sep",
  (select count(*) from orders o where o.created_at >= '2017-10-01' and o.created_at < '2017-11-01') as "Oct",
  (select count(*) from orders o where o.created_at >= '2017-11-01' and o.created_at < '2017-12-01') as "Nov",
  (select count(*) from orders o where o.created_at >= '2017-12-01' and o.created_at < '2018-01-01') as "Dec"

是否有更多 dynamic/scalable 的方式来做到这一点而不求助于动态 SQL?

编辑:

  1. 我会接受 SQL 服务器或 Postgres 的答案。我经常 运行 在两者上都这样查询。
  2. 至少输出应与给定的查询相匹配。但是垂直输出会更好。

您没有指定 DBMS,但如果您在 SQL 服务器中,您可以执行如下操作:

SELECT [1] as Jan,[2] as Feb,[3] as Mar,[4] as Apr,[5] as May,[6] as Jun,
[7] as Jul,[8] as Aug,[9] as Sep,[10] as Oct,[11] as Nov,[12] as Dec
FROM (
         SELECT MONTH(o.created_at) as pivotmonth
         FROM orders o
         WHERE YEAR(o.created_at) = 2017
) xt
PIVOT (
    COUNT(xt.pivotmonth) FOR xt.pivotmonth IN (
    [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) as pivottable

这样您每月可以获得 1 列。