Postgres 计数函数

Postgres Count Function

我在 Postgres 中有一个包含多个列的 table。出于这个问题的目的,我只说有 2 列,Employee ID 和 Date。我在下面有一个示例。

ID     |   DATE
F1     |   01/31/15
F2     |   01/31/15
E1     |   01/31/15
E2     |   01/31/15
F1     |   02/28/15
F2     |   02/28/15
E1     |   02/28/15
E2     |   02/28/15

您会注意到我有 4 名员工。 2 名是 "F" class 名员工,2 名是 "E" class 名员工。我有要计算的一月和二月的记录。

我想以这样的方式计算,以便查询为我分隔月份和年份(我在想

select to_char("Date", 'Mon') as mon,
       extract(year from "Date") as yyyy) 

并将 F 和 E 算作不同的列,这样我 return 结果如下:

 mon   | yyyy | F | E |
January| 2015 | 2 | 2 |
Februar| 2015 | 2 | 2 |

试试这个:

select to_char("date", 'Mon') as mon,
extract(year from "date") as yyyy ,
sum(case when l_part='E' then count end) as "E",
sum(case when l_part='F' then count end) as "F"
from(
     select left(id,1)as l_part, count(*),"date" from 
      table1 group by "date",l_part
   ) p group by "date";