2013-06-19 16 views
8

Hy. Ci sono record dei dipendenti nel mio database PostgreSQL qualcosa comeGroup by on Postgresql Data Ora

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

voglio utilizzare una query "SELECT tutti i codici e contarli avvenuto nel mese"

RISULTATO:

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

I ha utilizzato una query, ad esempio

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

La query precedente funziona bene ma i mesi elencati sono i n i registri sono in forma di numeri ed è difficile trovare che un mese appartenga a quale anno. In breve, voglio ottenere il risultato come menzionato sopra nella sezione RISULTATO. Grazie

risposta

17

Prova questo:

SELECT CODE, to_char(DATE, 'YYYY-MM'), count(CODE) 
FROM employee 
where 
group by CODE, to_char(DATE, 'YYYY-MM') 
1

provare uno qualsiasi dei

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; 
12

A seconda se si desidera che il risultato come testo o una data, è possibile anche scrivere in questo modo:

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

Quale nel vostro esempio restituirebbe questo, con DATE ancora un timestamp, che può essere utile se avete intenzione di fare ulteriori calcoli su di esso da conversioni sono necessarie:

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() accetta anche altri valori, per esempio quarter, year ecc Vedere la documentation per tutti i valori