Skip to content
Advertisement

SQL SERVER PIVOT like PEPSI comes under year then by months etc.. (refer attached image for a clear idea)

I am new to PIVOT… so i dont know whether is it possible or not with pivot.

Here is the table and the sample data i used

create table sales_history (brandcode varchar(10) , 
                            syear smallint, 
                            smonth smallint, 
                            salesvalues float )  


insert into sales_history values ('PPS', 2018,1, 256400.00), ('PPS', 2018,2, 278650.00), ('PPS', 2018,3, 236500.00)
insert into sales_history values ('CCL', 2018,1, 356200.00), ('CCL', 2018,2, 365100.00), ('CCL', 2018,3, 174300.00)
insert into sales_history values ('MND', 2018,1, 275200.00), ('MND', 2018,2, 415180.00), ('MND', 2018,3, 274500.00) 
insert into sales_history values ('PPS', 2019,1, 356400.00), ('PPS', 2019,2, 378650.00), ('PPS', 2019,3, 336500.00)
insert into sales_history values ('CCL', 2019,1, 456200.00), ('CCL', 2019,2, 465100.00), ('CCL', 2019,3, 274300.00)
insert into sales_history values ('MND', 2019,1, 375200.00), ('MND', 2019,2, 515180.00), ('MND', 2019,3, 374500.00) 

— PRIVOT Query

select *
 from (
 select *
  from sales_history
  ) as t1
  pivot 
   (sum (salesvalues) for syear IN ([2018],[2019])) 
  as pivot_brand_sales 

enter image description here

using the above query i got an output like in the attached

[please look the attachment for the required output that i was trying and the output i got using the above query ]

Advertisement

Answer

This is For SSRS

Step 1: Connect DataSource
Step 2: Create DataSet and paste your query in Query Box
Step 3: Click on Insert tab and Click on Matrix and you can put BrandCode into RowGroups
and sYear into ColumnGroups and than Smonth into ColumnGroups and SalesValues Put into Values And Click on Next Button
Step 4: If you dont want to Substotals and Grand Totals uncheck the check box and If you dont want to expand/collapse button on grid than please 
uncheck the checkbox and then click next and finish .
your result will be show as you want.

Regards 
Shehroz

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement