sql获取总数并同时使用pivot

ee7vknir  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(289)

我有两张这样的table

我有一个这样的数据集

并想得到所有的记过,代码,描述,到目前为止在任何月份(任何一年)的记过代码的犯罪总数,然后是每个月(任何一年)的记过代码的犯罪总数,基本上是这样的结果

我可以分别获得总数(使用groupby)和月度数据(使用pivot行作为列),但不知道如何在一个查询中获得它们。任何帮助都将不胜感激。

select * from (
 select 
        d.dem_code, 
        d.dem_code as dem_code_copy,
        d.dem_description, 
        case 
        when EXTRACT(month FROM off_datetime) = 1 then 'Jan'
        when EXTRACT(month FROM off_datetime) = 2 then 'Feb'
        when EXTRACT(month FROM off_datetime) = 3 then 'Mar'
        when EXTRACT(month FROM off_datetime) = 4 then 'Apr'
        when EXTRACT(month FROM off_datetime) = 5 then 'May'
        when EXTRACT(month FROM off_datetime) = 6 then 'Jun'
        when EXTRACT(month FROM off_datetime) = 7 then 'Jul'
        when EXTRACT(month FROM off_datetime) = 8 then 'Aug'
        when EXTRACT(month FROM off_datetime) = 9 then 'Sep'
        when EXTRACT(month FROM off_datetime) = 10 then 'Oct'
        when EXTRACT(month FROM off_datetime) = 11 then 'Nov'
        when EXTRACT(month FROM off_datetime) = 12 then 'Dec'
        end
        as "Month"    
    from demerit d
    left join offence o on d.dem_code = o.dem_code
    order by d.dem_code 
    )
    pivot(
    count(dem_code_copy)
    for "Month"
    in (
        'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
    )
)

这个查询给我每月的结果

select 
        d.dem_code, 
        d.dem_description,
        count(o.off_no) as total
    from demerit d
    left join offence o on d.dem_code = o.dem_code
    group by d.dem_code, d.dem_description
    order by d.dem_code

此查询提供总数

esbemjvw

esbemjvw1#

我只会使用条件聚合:

select d.dem_code, d.dem_description, 
       sum(case when EXTRACT(month FROM off_datetime) = 1 then 1 else 0 end) as Jan,
       sum(case when EXTRACT(month FROM off_datetime) = 2 then 1 else 0 end) as Feb
       sum(case when EXTRACT(month FROM off_datetime) = 3 then 1 else 0 end) as Mar,
       sum(case when EXTRACT(month FROM off_datetime) = 4 then 1 else 0 end) as Apr,
       sum(case when EXTRACT(month FROM off_datetime) = 5 then 1 else 0 end) as May,
       sum(case when EXTRACT(month FROM off_datetime) = 6 then 1 else 0 end) as Jun,
       sum(case when EXTRACT(month FROM off_datetime) = 7 then 1 else 0 end) as Jul,
       sum(case when EXTRACT(month FROM off_datetime) = 8 then 1 else 0 end) as Aug,
       sum(case when EXTRACT(month FROM off_datetime) = 9 then 1 else 0 end) as Sep,
       sum(case when EXTRACT(month FROM off_datetime) = 10 then 1 else 0 end) as Oct,
       sum(case when EXTRACT(month FROM off_datetime) = 11 then 1 else 0 end) as Nov,
       sum(case when EXTRACT(month FROM off_datetime) = 12 then 1 else 0 end) as Dec
from demerit d left join
     offence o
     on d.dem_code = o.dem_code
group by d.dem_code, d.dem_description;

相关问题