admin

Postgresql查询以获取一年内每月的计数

sql

在MySQL中

SELECT y, m, Count(users.created_date)
     FROM (
      SELECT y, m
      FROM
         (SELECT YEAR(CURDATE()) y UNION ALL SELECT YEAR(CURDATE())-1) years,
         (SELECT 1 m UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
           UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
           UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months) ym
       LEFT JOIN users
       ON ym.y = YEAR(FROM_UNIXTIME(users.created_date))
          AND ym.m = MONTH(FROM_UNIXTIME(users.created_date))
     WHERE
       (y=YEAR(CURDATE()) AND m<=MONTH(CURDATE()))
       OR
       (y<YEAR(CURDATE()) AND m>MONTH(CURDATE()))
     GROUP BY y, m;

Mysql输出

+------+----+----------------------+
| y    | m  | Count(users.created) |
+------+----+----------------------+
| 2012 |  5 |                 5595 |
| 2012 |  6 |                 4431 |
| 2012 |  7 |                 3299 |
| 2012 |  8 |                  429 |
| 2012 |  9 |                    0 |
| 2012 | 10 |                 3698 |
| 2012 | 11 |                 6208 |
| 2012 | 12 |                 5142 |
| 2013 |  1 |                 1196 |
| 2013 |  2 |                   10 |
| 2013 |  3 |                    0 |
| 2013 |  4 |                    0 |
+------+----+----------------------+

在PostgreSQL查询中

SELECT to_char(created_date, 'MM'),
       count(id)
FROM users
WHERE created_date >
      date_trunc('month', CURRENT_DATE) - INTERVAL '1 year'
GROUP BY 1

POSTGRESQL输出 PostgreSQL输出

我可以知道如何获得像mysql输出一样的postgresql输出。需要获取一年内当月数据的结果。


阅读 244

收藏
2021-06-07

共1个答案

admin

我假设您要查找的是count为0的行。如果是这种情况,则可以在表中使用generate_series和左连接并添加数据:

    SELECT to_char(i, 'YY'), to_char(i, 'MM'),
        count(id)
    FROM generate_series(now() - INTERVAL '1 year', now(), '1 month') as i
    left join users on (to_char(i, 'YY') = to_char(created_date, 'YY') 
                        and to_char(i, 'MM') = to_char(created_date, 'MM') and login_type = 1)
    GROUP BY 1,2;
2021-06-07