convert one row into columns

后端 未结 2 852
一个人的身影
一个人的身影 2021-01-20 17:14

This is my query. That show me results as described in the screen shot. Now i want to change it so it show me statues of the month in columns.

DECLARE @temp          


        
2条回答
  •  再見小時候
    2021-01-20 17:54

    Check out pivot tables;

    See http://msdn.microsoft.com/en-us/library/ms177410.aspx

    A simple query for a finite number of StatusTypeNames would be something like like;

    SELECT * FROM 
    (SELECT MonthName, StatusTypeName as attributeCol, StatusCount FROM @ResultsTable) rt 
    PIVOT ( MAX(StatusCount) FOR attributeCol in ([ToBeScheduled],[Complete])) as pvt
    ORDER BY MonthName
    

    Note the use of MAX. If there is chance you'll have multiple rows with the same monthname and status typename combination, then you might want to use SUM.

    To make use of dynamic columns as madhivinan suggests, you can follow this example. Scroll to the bottom.

    I tried to get it to work with your example, but because I had a couple of issues probably due to the fact I didn't have the tables. However, something like the following is what you are after.

    DECLARE @listCol VARCHAR(2000)
    DECLARE @query VARCHAR(4000)
    SELECT  @listCol = SELECT STUFF (( SELECT DISTINCT '],[' + 
                        StatusTypeName FROM @ResultsTable ORDER BY '],[' + 
                        StatusTypeName FOR XML PATH ('')), 1, 2, '') + ']'
    
    
    SET @query =
    'SELECT * FROM
          (SELECT MonthNameCol, StatusTypeName as attributeCol, StatusCount FROM @ResultsTable) rt
    PIVOT ( MAX(StatusCount) FOR attributeCol in ('+@listCol+')) AS pvt ORDER BY MonthNameCol'
    
    EXECUTE (@query)
    

    It's not exactly right, but it's a starting point.

    Good luck.

提交回复
热议问题