how to transform sql simpler view to dynamic view

Ann 1 Reputation point
2020-09-06T12:25:21.453+00:00

Hi Export,

I have Source data that has already in summary format

22882-image.png

How to use the SQL to transform it to below

22873-image.png

DECLARE   
    @columns NVARCHAR(MAX) = '',  
    @sql     NVARCHAR(MAX) = '';  
  
		-- select the category names  
		SELECT   
			@columns+=QUOTENAME(RptPeriod) + ','  
		FROM   
			(  
			select distinct RptPeriod from  
			Vw_NEWStock#   
			) as NewPeiord  
  
		ORDER BY   
			RptPeriod;  
  
  
		-- remove the last comma  
		SET @columns = LEFT(@columns, LEN(@columns) - 1);  
  
		PRINT @columns  
		-- construct dynamic SQL  
  
  
		SET @sql ='  
		SELECT * FROM     
		(  
			SELECT   
				Title, RptPeriod,HGpname,Pcs,docvalue  
			FROM   
			   Vw_NewStock#  
		) DynamicViewNewStock  
		PIVOT(  
			Sum(Docvalue)   
			FOR RptPeriod IN ('+ @columns +')  
		) AS pivot_table;'  
END  
  
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 128.7K Reputation points MVP Volunteer Moderator
    2020-09-06T15:35:48.703+00:00

    It's not really clear what your question is. You are posting some code. What does that code do?

    In any case, why do you want to use SQL for this? You have some data which you seem to want to present in some format. That format is often best achieved in the presentation layer. Several reporting components have built-in pivoting capabilities.

    If you really want to do this in SQL, I have written how to do dynamic pivots here: http://www.sommarskog.se/dynamic_sql.html#pivot.

    If you want someone to write a query for you, you should post CREATE TABLE statements for your table(s) and INSERT statements with sample data, enough to illustrate all angles of the problem, together with the expected result. Then we can copy and paste into a query window to develop a tested solution.

    But chances are good that you should not use SQL at all for this.

    1 person found this answer helpful.
    0 comments No comments

  2. MelissaMa-msft 24,241 Reputation points Moderator
    2020-09-07T07:01:26.36+00:00

    Hi @Ann ,

    Please refer below:

    DECLARE   
         @columns NVARCHAR(MAX) = '',  
         @sql     NVARCHAR(MAX) = '';  
      
             SELECT   
                 @columns+=QUOTENAME(RptPeriod) + ','  
             FROM   
                 (  
                 select distinct RptPeriod from  
                 Vw_NEWStock#   
                 ) as NewPeiord  
             ORDER BY   
                 RptPeriod;  
          
             SET @columns = LEFT(@columns, LEN(@columns) - 1);  
      
            DECLARE  @columns1  NVARCHAR(MAX) = '',  
     @columns2  NVARCHAR(MAX) = '';  
      
             SELECT   
                 @columns1+='MAX('+QUOTENAME(RptPeriod)+') '+ QUOTENAME(RptPeriod) + ','  
             FROM   
                 (  
                 select distinct RptPeriod from  
                 Vw_NEWStock#   
                 ) as NewPeiord  
             ORDER BY   
                 RptPeriod;  
          
             SET @columns1= LEFT(@columns1, LEN(@columns1) - 1);  
          
         SELECT   
                 @columns2+='SUM('+QUOTENAME(RptPeriod)+')'+ ','  
             FROM   
                 (  
                 select distinct RptPeriod from  
                 Vw_NEWStock#   
                 ) as NewPeiord  
             ORDER BY   
                 RptPeriod;  
          
             SET @columns2= LEFT(@columns2, LEN(@columns2) - 1);  
      
             SET @sql =';WITH CTE AS(  
             SELECT Title [Sum of Pcs],HGPname,'+ @columns1 +' FROM     
             (  
                 SELECT   
                     Title, RptPeriod, HGpname,Pcs,docvalue  
                 FROM   
                    Vw_NewStock#  
             ) DynamicViewNewStock  
             PIVOT(  
                 Sum(Pcs)   
                 FOR RptPeriod IN ('+ @columns +')  
             ) AS pivot_table  
      GROUP BY pivot_table.title,pivot_table.HGPname  
      )  
     SELECT * FROM   
     (SELECT * FROM CTE   
     UNION ALL  
     select ''Grand Total'' [Sum of Pcs],null HGPname,'+@columns2+' FROM CTE) A  
     ORDER BY [Sum of Pcs] desc'  
      
              EXECUTE sp_executesql  @sql  
    

    Example output:
    23025-pivot.png
    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.