sql >> Database >  >> RDS >> PostgreSQL

Maandelijkse totalen uit meerdere kolommen weergeven in PostgreSQL

SQL Fiddle

select
    to_char(('2012-' || m || '-01')::date, 'Month'),
    thisyear, lastyear, totalthisyear, totallastyear
from (
    select
        extract(month from m) as m,
        sum(case
            when firstexam between '2013-01-01' and '2013-12-31' then firstexam_count
            else 0 end
        ) as thisyear,
        sum(case
            when firstexam between '2012-01-01' and '2012-12-31' then firstexam_count
            else 0 end
        ) as lastyear,
        sum(case
            when lastexam between '2013-01-01' and '2013-12-31' then lastexam_count
            else 0 end
        ) as totalthisyear,
        sum(case
            when lastexam between '2012-01-01' and '2012-12-31' then lastexam_count
            else 0 end
        ) as totallastyear
    from
        generate_series (
            '2012-01-01'::date, '2013-12-31', '1 month'
        ) g(m)
        left join (
            select count(*) as firstexam_count, date_trunc('month', firstexam) as firstexam
            from patient_info
            where firstexam between '2012-01-01' and '2013-12-31'
            group by 2
        ) pif on firstexam = m
        left join (
            select count(*) as lastexam_count, date_trunc('month', lastexam) as lastexam
            from patient_info
            where lastexam between '2012-01-01' and '2013-12-31'
            group by 2
        ) pil on lastexam = m
    group by 1
) s
order by m



  1. Is Entity Framework gekoppeld aan SQL Server?

  2. Gegevens invoegen na het maken van een index op een lege tabel of het creëren van een unieke index na het invoegen van gegevens op Oracle?

  3. Oracle SQL retourneert rijen op willekeurige wijze wanneer er geen order by-clausule wordt gebruikt

  4. MySQL:genest GROUP_CONCAT