Imagine two questions from an online survey:
Result stored in mysql db column \"q1\" as
Thanks @user2864740 and @sgeddes for your prompt replies.
SURVEY SAYS: It is NOT possible to sort returned columns in a SELECT statement using mysql without using dynamic sql.
The solution I came up with uses a temporary table and is similar to the example below. While perhaps less than ideal, it answered the mail for what I needed. Curious if there is a better way to do the same thing or if I messed anything else up below.
DROP TEMPORARY TABLE IF EXISTS orderedSums;
SET @q1Sum = (SELECT SUM(q1) FROM myTable);
SET @q2Sum = (SELECT SUM(q2) FROM myTable);
CREATE TEMPORARY TABLE orderedSums (
qNum VARCHAR(5),
qSum INT
);
INSERT INTO orderedSums
VALUES ('q1Sum', @q1Sum),('q2Sum', @q2Sum);
SELECT qNum, qSum
FROM orderedSums
ORDER BY qSum DESC;
Returns multiple rows of SUMs sorted in descending order from myTable.
Assuming I'm understanding your question correctly, you could use a case
statement:
SELECT CASE WHEN SUM(q1) > SUM(q2) THEN SUM(q1) ELSE SUM(q2) END AS q1Sum,
CASE WHEN SUM(q1) > SUM(q2) THEN SUM(q2) ELSE SUM(q1) END AS q2Sum
FROM myTable
Actually this would mislabel the columns -- you cannot alter the name of the column without using dynamic sql
.