DYNAMICALLY
Mark as answered if this post solved your problem and Vote as helpful if this post was useful.
-- structure and data
use tempdb;
create table TabV (
ItemName varchar(20),
Version int,
Quantity int
);
insert into TabV values
('I1',1,10), ('I2',2,15), ('I3',1,8), ('I4',2,9);
select * from TabV;
-- code 2
declare @ListaCol varchar(500);
set @ListaCol='';
select @ListaCol += '['+ cast([Version] as varchar) +'],'
from (select distinct [Version] from TabV) as T;
set @ListaCol=left(@ListaCol, datalength(@ListaCol)-1);
--print @ListaCol;
--
declare @ComandoSQL varchar(1500);
set @ComandoSQL = 'select ItemName,' + @ListaCol + ' from TabV pivot (sum(Quantity) ' +
'for [Version] in ('+@ListaCol+')) as P;';
--print @ComandoSQL;
execute (@ComandoSQL);
Mark as answered if this post solved your problem and Vote as helpful if this post was useful.
No comments:
Post a Comment