SQL Server Pivot or UnPivot so confused -


i working on creating report using sql server database. unfortunately not able figure out how it.

here database structure:

create table #mytable (     [foryear] [smallint] not null,     [formonth] [tinyint] not null,     [trainingdonethismonth] [bit] null,     [foodqualitystatus] [bit] null,     [noofalldrugtests] [int] null,     [noofallalcoholtests] [int] null )  insert #mytable  values (2016, 1, 1, 0, 5, 10), (2016, 2, 0, 1, 15, 5),        (2016, 3, 1, 0, 20, 15), (2016, 4, 0, 1, 5, 25),        (2016, 5, 1, 0, 10, 30) 

i need report in following format. column names converted rows , corresponding values transformed.

report sample

i have tried pivot , unpivot not able desired results please help.

this trying:

select 1,2,3 (   select noofallalcoholtests,formonth   #mytable ) d pivot (   sum(noofallalcoholtests)   formonth in ([1],[2],[3]) ) piv; 

unpivot pivot:

select  objective,          [january],         [february],         [march],         [april],         [may],         case when objective in ('noofalldrugtests','noofallalcoholtests') cast([january]+[february]+[march]+[april]+[may] nvarchar(10))              else cast([january]+[february]+[march]+[april]+[may] nvarchar(10)) +' true, ' +              cast(5 -( [january]+[february]+[march]+[april]+[may]) nvarchar(10)) +' false'               end finaltotal (     select *     (         select  datename(month,dateadd(month,[formonth]-1,'1970-01-01')) d,                 cast([trainingdonethismonth] int) [trainingdonethismonth],                 cast([foodqualitystatus] int) [foodqualitystatus],                 [noofalldrugtests],                 [noofallalcoholtests]         #mytable         ) d     unpivot (       [values] [objective] in ([trainingdonethismonth],[foodqualitystatus],[noofalldrugtests],[noofallalcoholtests])     ) unpvt ) p pivot (     sum([values]) d in ([january],[february],[march],[april],[may]) ) pvt 

output:

objective               january february    march   april   may finaltotal foodqualitystatus       0       1           0       1       0   2 true, 3 false noofallalcoholtests     10      5           15      25      30  85 noofalldrugtests        5       15          20      5       10  55 trainingdonethismonth   1       0           1       0       1   3 true, 2 false 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -