1

How can I optimizate this SQL Query?

(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '0') AS a,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '1') AS b,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '2') AS c

2 Answers 2

7

When you want to do a pivot in MySQL you can do Aggregate on a Case statement

SELECT 
    SUM ( CASE WHEN other_same_field  = 0 THEN same_field ELSE 0 END) as A,
    SUM ( CASE WHEN other_same_field  = 1 THEN same_field ELSE 0 END) as B,
    SUM ( CASE WHEN other_same_field  = 2 THEN same_field ELSE 0 END) as C
FROM same_table
WHERE other_same_field IN (0, 1, 2)
Sign up to request clarification or add additional context in comments.

3 Comments

Which one is actually better in performance, yours or @FreshPrinceOfSO's query?
@cawecoy I would expect the perf to be about the same, but they yield different results (1 row, 3 columns) vs (3 rows, 2 columns). The deciding factor would be how you intend to use the results. If you can I would go with FreshPrinceOfSO's since the SQL is cleaner. But if you need it in the format of 3 columns and you can't/or don't want to do the projection on the client then you'd need to go with SUM(CASE..
Thank you ConradFrix and @FreshPrinceOfSO.
4

This will give you a vertical result.

SELECT other_same_field, SUM(same_field)
FROM same_table
WHERE other_same_field IN (0, 1, 2)
GROUP BY other_same_field

2 Comments

The wouldn't match the output of the original statement.
I still think it's a valid answer on how to optimize the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.