10

Hy. There are employee records in my postgresql database something like

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

I want to use a query "SELECT ALL CODES AND COUNT THEM THAT OCCURRED IN THE MONTH"

RESULT:

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

I did use a query i.e.

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

The above query runs fine but the months listed in the records are in form of numbers and its hard to find that a month belongs to which year. In short I want to get the result just like mention above in the RESULT section. Thanks

3 Answers 3

18

Try this:

SELECT CODE, to_char(DATE, 'YYYY-MM'), count(CODE)
FROM employee
where 
group by CODE, to_char(DATE, 'YYYY-MM')
Sign up to request clarification or add additional context in comments.

Comments

13

Depending on whether you want the result as text or a date, you can also write it like this:

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

Which in your example would return this, with DATE still a timestamp, which can be useful if you are going to do further calculations on it since no conversions are necessary:

 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() also accepts other values, for instance quarter, year etc. See the documentation for all values

1 Comment

It is possible to specify date_trunc('month', DATE) AS mydate and then use mydate in the rest of the query (e.g. in GROUP BY).
1

Try any of

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.