我有两张这样的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
此查询提供总数
1条答案
按热度按时间esbemjvw1#
我只会使用条件聚合: