How to rotate columns into rows

  • Hi All,

    I have the below query which retuns one row of data, how can I get the data grouped on the column aliases so i can have five rows for each column with the count side by side.

    SELECT COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) < 1 THEN 1

    END) AS '< 1' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 1

    AND DATEDIFF(dd, createdon, modifiedon) <= 3 THEN 1

    END) AS '>1 and <= 3' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 3

    AND DATEDIFF(dd, createdon, modifiedon) <= 5 THEN 1

    END) AS '>3 and <= 5' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 5

    AND DATEDIFF(dd, createdon, modifiedon) <= 10 THEN 1

    END) AS '>5 and <=10' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 10 THEN 1

    END) AS '>10'

    FROM Table

    Thanks in advance

  • Try this

    SELECT range , Count FROM

    (

    SELECT COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) < 1 THEN 1

    END) AS '< 1' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 1

    AND DATEDIFF(dd, createdon, modifiedon) <= 3 THEN 1

    END) AS '>1 and <= 3' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 3

    AND DATEDIFF(dd, createdon, modifiedon) <= 5 THEN 1

    END) AS '>3 and <= 5' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 5

    AND DATEDIFF(dd, createdon, modifiedon) <= 10 THEN 1

    END) AS '>5 and <=10' ,

    COUNT(CASE WHEN DATEDIFF(dd, createdon, modifiedon) > 10 THEN 1

    END) AS '>10'

    FROM Table

    ) P

    UNPIVOT

    (

    Count for range IN

    (

    [< 1], [>1 and <= 3], [>3 and <= 5], [>5 and <=10], [>10]

    )

    ) AS UP

    Vaibhav K Tiwari
    To walk fast walk alone
    To walk far walk together

  • Convert the existing query to derived table and apply UNPIVOT operator on the columns.

    --Ramesh


  • Thanks this did the trick.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply