Skip to content
Advertisement

How to Sort this MySQL Query

I am trying to insert the ORDER BY in this query to sort the Total column:

SELECT GROUP_CONCAT(CONCAT('SELECT ''', COLUMN_NAME,''' MyColumns, SUM(`', COLUMN_NAME,'`) Total FROM mydb.source_table') SEPARATOR 'n UNION ALL n')
INTO @sql
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'mydb' 
  AND TABLE_NAME   = 'source_table'
  AND COLUMN_NAME NOT IN ('ID', 'Name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP PREPARE stmt;

With the following result:

+-----------+-----------+
| MyColumns |   Total   |
+-----------+-----------+
| ABC       |     67.00 |
+-----------+-----------+
| DEF       |     40.00 |
+-----------+-----------+
| GHI       |     33.00 |
+-----------+-----------+
| JKL       |     39.00 |
+-----------+-----------+
| MNO       |     33.00 |
+-----------+-----------+

Here’s what I have tried so far but no luck:

1. mydb.source_table ORDER BY Total
2. SEPARATOR 'nUNION ALLn' ORDER BY 'Total' ASC
3. SEPARATOR 'nUNION ALLn ORDER BY Total' ASC
4. AND COLUMN_NAME NOT IN ('ID', 'Name') ORDER BY 'Total' ASC;
5. ORDER BY 'Total' ASC SEPARATOR 'nUNION ALLn'

Advertisement

Answer

I think you want:

SELECT CONCAT(
    GROUP_CONCAT(
        'SELECT ''', COLUMN_NAME,''' MyColumns, SUM(`', COLUMN_NAME,'`) Total FROM mydb.source_table' 
        SEPARATOR 'n UNION ALL n'
    ),
    'nORDER BY Total DESC'
)
INTO @sql
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = 'mydb' 
    AND TABLE_NAME   = 'source_table'
    AND COLUMN_NAME NOT IN ('ID', 'Name');

Rationale: the ORDER BY clause should go after all UNION ALL subqueries – so it needs to be outside of the GROUP_CONCAT(), in an outer CONCAT().

Also please note that you don’t need CONCAT() within GROUP_CONCAT(): MySQL does that by default already.

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