sqlsql-servert-sqlsql-server-2008ssms-2014

Convert rows to columns in SQL Server Management Studio


I'm posting the query below which I used to retrieve the data and output how it shows and how do I need also .. please let me know how can I convert rows to columns data


Solution

  • Just use conditional aggregation since the columns are constant.

    select
        BarCdmID
        , AME = MAX(case when Facility_MisFacID = 'AME' then MyCount end) 
        , AMV = MAX(case when Facility_MisFacID = 'AMV' then MyCount end) 
        , BHV = MAX(case when Facility_MisFacID = 'BHV' then MyCount end) 
        , BRV = MAX(case when Facility_MisFacID = 'BRV' then MyCount end) 
        , EOR = MAX(case when Facility_MisFacID = 'EOR' then MyCount end) 
        , IPA = MAX(case when Facility_MisFacID = 'IPA' then MyCount end) 
        , IPB = MAX(case when Facility_MisFacID = 'IPB' then MyCount end) 
        , LTC = MAX(case when Facility_MisFacID = 'LTC' then MyCount end) 
        , OHW = MAX(case when Facility_MisFacID = 'OHW' then MyCount end) 
    from
    (
        Select BarCdmID = LEFT(BarCdmID, 2)
            , Facility_MisFacID
            , MyCount = count(*)
        from BarCdm_Facil
        group by LEFT(BarCdmID, 2)
            , Facility_MisFacID
    
    ) x
    group by X.BarCdmID
    order by BarCdmID