-1

I have a table with data like this :

enter image description here

I need to write a T-SQL query to transform the data to make a result like this :

enter image description here

Alfin E. R.
  • 741
  • 1
  • 7
  • 24
Aniel
  • 39
  • 5

1 Answers1

0

You can use some sort of dynamic query by executing a SQL statement from a string variable

the concept is pretty much as follows:

first, declare the variable

DECLARE @pivotcolumns NVARCHAR(MAX) = '', 
    @sqlquery     NVARCHAR(MAX) = '';

get all the mode_code and store them into a variable @pivotcolumns

SELECT 
    @pivotcolumns+=QUOTENAME(mode_code) + ','
FROM 
    the_table
ORDER BY 
    mode_code;

SET @pivotcolumns = LEFT(@pivotcolumns, LEN(@pivotcolumns) - 1);

if we print the @pivotcolumns it will become something like '0','1','2','...'

after you get all the column, parse them into a string for SQL query

SET @sqlquery ='
SELECT * FROM (
    select mode_code, time_spent
    from the_table) t
PIVOT(
    SUM(time_spent) 
    FOR mode_code IN ('+ @pivotcolumns +')
) AS pivot_table;';

After you finish making a string of an SQL query, then we can execute it using sp execute SQL

EXECUTE sp_executesql @sqlquery;
Alfin E. R.
  • 741
  • 1
  • 7
  • 24
  • Using variable assignment to concatenate strings (`SELECT @Column += ....`) is [undocumented and unreliable](https://marc.durdin.net/2015/07/concatenating-strings-in-sql-server-or-undefined-behaviour-by-design/). It does not always work as expected. You should either use `STRING_AGG` (if using a version that supports it), or use [XML Extensions](https://stackoverflow.com/questions/5031204/does-t-sql-have-an-aggregate-function-to-concatenate-strings/5031297#5031297) to concatenate the rows into a variable – GarethD Jun 16 '20 at 06:32