以下のように、ピボット テーブルを作成するストアド プロシージャを作成しました。問題は、ヌルをゼロに変更しないため、期待どおりに機能しないことです。正しい方向を教えてください。
create procedure sp_system_counts
as
declare @columns nvarchar(max)
declare @columnscondition nvarchar(max)
declare @query nvarchar(max)
select distinct systemgroup, systemgroupsortorder into #temp_table_system_group
from systemgroups
where systemgroup not like 'N/A'
order by systemgroupsortorder
select @columns = isnull(@columns + ',', '') + '[' + convert(varchar, systemgroup) + ']' FROM #temp_table_system_group
select @columnscondition = + isnull(@columnscondition + ' or ', '') + '[' + convert(varchar, systemgroup) + '] <> 0' FROM #temp_table_system_group
--select @columns
create table #temp_systems (
systemid int,
systemnane varchar(max),
region varchar(50),
systemgroup varchar(50),
remsid int,
remscode int)
insert into #temp_systems
select distinct sy.systemid, sy.systemname, co.region, syg.systemgroup, re.remsid, re.remscode
from systems sy
inner join servers se on sy.systemid = se.systemid and sy.systemid = sy.systemid
inner join rems re on se.remsid = re.remsid
inner join cities ci on re.cityid = ci.cityid
inner join countries co on ci.countryid = co.countryid
inner join systemmodels sym on sy.systemmodelid = sym.systemmodelid
inner join systemtypes syt on sym.systemtypeid = syt.systemtypeid
inner join systemgroups syg on syt.systemgroupid = syg.systemgroupid
where syg.systemgroup not like 'N/A'
order by syg.systemgroup
set @query = '
select region, ' + @columns + '
from (
select distinct region, systemgroup, cnt = isnull(count(systemid),0) from #temp_systems
group by region, systemgroup
with rollup) p
pivot (sum (cnt) for systemgroup in (' + @columns + ')) as asd
where (' + @columnscondition +')'
execute(@query)
drop table #temp_table_system_group
drop table #temp_systems