Skip to content
Advertisement

SQL/MYSQL /Transpose table / Columns into rows and rows sum as column with new header

i have a table like this

Its simple in Excel sheets but im stuck in MySql Appreciate the help Thanks

— SeasonType,Sacks,SacksYards are columns

— union all attempt column sacks,sacksyards table — — fantasydefencegame

Advertisement

Answer

This should fairly give you some ideas. Supposing we are using a test database named testdb and your original table is named test which has 3 columns i.e a,b,c . The three rows in the table are just like what you provided before. Next we can proceed to create a stored procedure. Note: The reason behind using a prepared statement to get the sum value for each column is due to the rules that column names have to be hardcoded , which can not be replaced with variables. e.g select sum(a) from test; can not be written as select sum(@column_name) from test;. By using a prepared statement, we can hardcode the column name dynamically.

Finally we call the procedure to get the desired output:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement