Search code examples
sqlsql-servercountunpivotlateral-join

SQL query to change column names to single column value


I'm using SQL Server. Not sure what version, but it's still supported. I have a table that has 3 columns that I'm interested in. I need to change the column names in a 'hardware' column with the counts for each. Right now I have the following:

SELECT 
    COUNT(a.EAMacBook13) AS 'MacBook13', 
    COUNT(a.EAMacBook16) AS 'MacBook16', 
    COUNT(a.EAStandLaptop) AS 'StandLaptop' 
FROM 
    Employee AS e, EmpAttributes AS a 
WHERE 
    a.EAEmpID = e.EmpID AND e.EmpProjID = 1

enter image description here

where instead I need something like:

enter image description here

Is this possible?


Solution

  • You can do it with a simple union all:

    SELECT 'MacBook13' "Hardware", Count(a.EAMacBook13) "Count"
    FROM Employee as e, EmpAttributes as a WHERE a.EAEmpID = e.EmpID and e.EmpProjID = 1
    union all 
    SELECT 'MacBook16' "Hardware", Count(a.EAMacBook16)  "Count"
    FROM Employee as e, EmpAttributes as a WHERE a.EAEmpID = e.EmpID and e.EmpProjID = 1
    union all 
    SELECT 'StandLaptop' "Hardware", Count(a.EAStandLaptop)  "Count"
    FROM Employee as e, EmpAttributes as a WHERE a.EAEmpID = e.EmpID and e.EmpProjID = 1
    

    Depending on your RDBMS, you might have access to UNPIVOT which would make this less writing.

    You could also use a CTE so that (if your RDBMS supports materializing them) you do less work:

    with cte as (
      SELECT Count(a.EAMacBook13) as EAMacBook13, Count(a.EAMacBook16) as EAMacBook16, Count(a.EAStandLaptop) as EAStandLaptop
      FROM Employee as e, EmpAttributes as a WHERE a.EAEmpID = e.EmpID and e.EmpProjID = 1
    )
    SELECT 'MacBook13' "Hardware", EAMacBook13 "Count"
    FROM  cte
    union all 
    SELECT 'MacBook16' "Hardware", MacBook16 "Count"
    FROM cte
    union all 
    SELECT 'StandLaptop' "Hardware", StandLaptop "Count"
    FROM cte
    

    You will have to list out the possible Hardware values unless you use some degree of dynamic SQL.