Вы также можете использовать Cursor
или while
l oop для получения сведений о столбцах и динамического построения столбцов с ненулевой суммой.
попробуйте выполнить следующее:
create table test_tab (country varchar(100) ,[0-1 days] int,[1-2 days] int,[2-3 days] int,[3-4 days] int,[4-5 days] int,[5-6 days] int,[6-7 days] int,[7-8 days] int,[8-9 days] int,[9-10 days] int,[>10 days] int)
insert into test_tab select 'country_1' , 1, 56, 4, 6, 3, 2, 0, 0, 0, 0, 0
insert into test_tab select 'country_2' , 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_3' , 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_4' , 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_5' , 1, 3, 0, 1, 1, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_6' , 1, 11, 2, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_7' , 1, 31, 9, 4, 2, 1, 0, 0, 0, 0, 0
insert into test_tab select 'country_8' , 1, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_9' , 1, 13, 2, 3, 0, 0, 1, 0, 0, 0, 0
insert into test_tab select 'country_10', 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0
insert into test_tab select 'country_11', 1, 5, 1, 0, 1, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_12', 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
insert into test_tab select 'country_13', 1, 5, 1, 1, 0, 1, 0, 0, 0, 0, 0
select * from dbname.schemaname.test_tab
declare @non_zero_columns varchar(max) = ''
declare cur cursor fast_forward for
select name from dbname.sys.columns
where object_id = object_id('dbo.test_tab') and name like '%days' --hope there is some kind of pattern
declare @col_name sysname
declare @query nvarchar(max)
declare @result int
open cur
fetch next from cur into @col_name
while @@FETCH_STATUS = 0
begin
set @query = 'set @result = (select sum('+quotename(@col_name)+') from dbname.schemaname.test_tab)'
exec sp_executesql @query, N'@result int out', @result out
if (@result <> 0)
set @non_zero_columns = @non_zero_columns + ',' + quotename(@col_name)
fetch next from cur into @col_name
end
close cur
deallocate cur
declare @final_dynamic_sql varchar(max) = 'select country '+@non_zero_columns+' from dbname.schemaname.test_tab'
print (@final_dynamic_sql)
exec (@final_dynamic_sql)
НТН!