hi
i took a stab at this
please check verify and let me know !!!!
some things have been hard coded
... if you dont want hard coded please let me know
hope it helps .. i love feedback thanks
-)
drop create sample data ....
drop table #sampledata
go
create table #sampledata
(
centre varchar(100),
recruitment int ,
induction int,
training int,
recognition int
)
go
insert into #sampledata select 'Branch 1',3,3,3,3
insert into #sampledata select 'Branch 1',3,4,3,4
insert into #sampledata select 'Branch 1',5,4,4,3
insert into #sampledata select 'Branch 1',2,2,5,5
insert into #sampledata select 'Branch 1',3,3,3,3
insert into #sampledata select 'Branch 1',4,4,4,4
insert into #sampledata select 'Branch 1',5,5,5,5
insert into #sampledata select 'Branch 1',5,4,4,3
insert into #sampledata select 'Branch 1',5,4,3,3
insert into #sampledata select 'Branch 1',4,4,4,5
insert into #sampledata select 'Branch 1',5,5,5,5
insert into #sampledata select 'Branch 1',5,4,4,3
insert into #sampledata select 'Branch 1',4,1,3,1
insert into #sampledata select 'Branch 5',5,5,5,4
insert into #sampledata select 'Branch 5',5,4,3,3
insert into #sampledata select 'Branch 5',5,4,5,2
insert into #sampledata select 'Branch 5',3,4,4,4
insert into #sampledata select 'Branch 5',3,4,5,3
insert into #sampledata select 'Branch 4',5,4,4,4
insert into #sampledata select 'Branch 4',5,4,4,4
insert into #sampledata select 'Branch 4',5,5,5,5
go
sql ...
DROP TABLE #abc
go
;
WITH cte
AS (SELECT centre,
recruitment AS ko,
'Recruitment' AS ok
FROM #sampledata
UNION ALL
SELECT centre,
induction,
'Induction'
FROM #sampledata
UNION ALL
SELECT centre,
training,
'Training'
FROM #sampledata
UNION ALL
SELECT centre,
recognition,
'Recognition'
FROM #sampledata)
SELECT centre,
ko,
ok
INTO #abc
FROM cte
go
DECLARE @cols AS NVARCHAR(max),
@query AS NVARCHAR(max)
SELECT @cols = Stuff((SELECT DISTINCT ',' + Quotename(centre)
FROM #abc
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1,
'')
DECLARE @count1 VARCHAR
SELECT @count1 = Count(DISTINCT centre)
FROM #abc
DECLARE @cols1 AS NVARCHAR(max),
@query1 AS NVARCHAR(max)
SELECT @cols1 = Stuff((SELECT DISTINCT '+' + Quotename(centre)
FROM #abc
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1
, '')
SET @cols1 = 'cast((' + @cols1 + ')/' + @count1
+ '.0 as decimal(5,2))'
SET @query = N'SELECT ok as '' '', ' + @cols + ',' + @cols1
+ ' as total'
+ N' from ( select centre, cast(ko as decimal(5,2)) as ko, ok from #abc ) x pivot ( avg(ko) for Centre in ('
+ @cols + N') ) p '
PRINT @query
EXEC Sp_executesql
@query;
