Show rows as columns

  • Hi everyone,

    I have the following table

    create table temp (status int,name varchar(20))

    insert table temp values(4,'with applicant')

    insert table temp values(3'in review')

    insert table temp values(3,'in review')

    insert table temp values(4,'with applicant')

    insert table temp values(4,'with applicant')

    insert table temp values(4,'with applicant')

    insert table temp values(4,'with applicant')

    insert ttable emp values(1,'cancelled')

    I want to show up my results as

    create table temp2(inreview varchar(20),withapplicant varchar(20),cancelled varchar(20))

    insert temp2 values (2,4,1)

    -- count of names

    Any help is really appreciated

  • You can use Pivot function to do this..

    SELECT [in review] as 'inreview',[with applicant] as 'withapplicant',[cancelled] as 'cancelled'

    FROM

    (SELECT [status],[name]

    FROM temp) AS SourceTable

    PIVOT

    (

    Count([status])

    FOR [name] IN ([with applicant],[in review],[cancelled])

    ) AS PivotTable;

    For more information checkout this link http://msdn.microsoft.com/en-us/library/ms177410.aspx

  • You can also do a crosstab which tend to work better as the queries get more complex ...

    selectinReview = sum(case when name = 'in review' then 1 end)

    ,withApplicant = sum(case when name = 'with applicant' then 1 end)

    ,cancelled = sum(case when name = 'cancelled' then 1 end)

    from @temp;

    And btw, in your example there are 5 'with applicant' entries, not 4.

    └> bt



    Forum Etiquette: How to post data/code on a forum to get the best help[/url]

  • Thanks both. That helped

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

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