9

海。我的 postgresql 数据库中有员工记录,例如

 CODE     DATE       COUNT 
"3443"   "2009-04-02"  3
"3444"   "2009-04-06"  1
"3443"   "2009-04-06"  1
"3443"   "2009-04-07"  7

我想使用查询“选择所有代码并计算当月发生的代码”

结果:

 CODE     DATE     COUNT 
"3443"   "2009-04"  3
"3441"   "2009-04"  13
"3442"   "2009-04"  11
"3445"   "2009-04"  72

我确实使用了一个查询,即

SELECT CODE,date_part('month',DATE),count(CODE)
FROM employee
where 
group by CODE,DATE

上述查询运行良好,但记录中列出的月份是数字形式,很难找到月份属于哪一年。简而言之,我想得到结果,就像上面在结果部分中提到的那样。谢谢

4

3 回答 3

18

试试这个:

SELECT CODE, to_char(DATE, 'YYYY-MM'), count(CODE)
FROM employee
where 
group by CODE, to_char(DATE, 'YYYY-MM')
于 2013-06-19T06:30:25.917 回答
12

根据你想要的结果是文本还是日期,你也可以这样写:

SELECT CODE, date_trunc('month', DATE), COUNT(*)
    FROM employee
    GROUP BY CODE, date_trunc('month', DATE);

在您的示例中,它会返回这个,DATE 仍然是一个时间戳,如果您要对其进行进一步计算,这可能很有用,因为不需要转换:

 CODE     DATE     COUNT 
"3443"   "2009-04-01"  3
"3441"   "2009-04-01"  13
"3442"   "2009-04-01"  11
"3445"   "2009-04-01"  72

date_trunc()还接受其他值,例如等。有关所有值quarteryear请参阅文档

于 2013-06-19T09:23:18.367 回答
1

尝试任何一个

SELECT CODE,count(CODE),
    DATE as date_normal, 
    date_part('year', DATE) as year, 
    date_part('month', DATE) as month, 
    to_timestamp(
        date_part('year', DATE)::text 
        || date_part('month', DATE)::text, 'YYYYMM')
        as date_month
FROM employee
where 
group by CODE,DATE;
于 2013-06-19T06:32:14.477 回答