Postgresql查询在一年内获得每月的计数

时间:2016-10-14 16:57:24

标签: sql database postgresql postgresql-9.5

在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 |
+------+----+----------------------+

** IN POSTGRESQL QUERY **

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 OUTPUT postgresql output

我是否知道如何将postgresql输出与mysql输出一样。需要在一年的数据内获得当月的结果。

1 个答案:

答案 0 :(得分:2)

我假设您要查找的是计数为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;