0

I have a SELECT Query which should have several nested SELECT Queries from the same table, but different WHERE clauses to produce new columns.

The problem is that each sub query in its single form runs good, but when they turn into sub-queries, MySql throws an ERROR.

Here is My SQL :

SELECT user, 
(SELECT SUM(amount) from my_table WHERE type='form1' group by user) as form1,
(SELECT SUM(amount) from my_table WHERE type='form2' group by user) as form2,
(SELECT SUM(amount) from my_table WHERE type='form3' group by user) as form3,
(SELECT SUM(amount) from my_table WHERE type='form4' group by user) as form4,
(SELECT SUM(amount) from my_table WHERE type='form5' group by user) as form5,
(SELECT SUM(amount) from my_table WHERE type='form6' group by user) as form6
from my_table group by user;

I want the Query to produce this structure:

user | form1 | form2 | form3 | form4 | form5 | form6
     |       |       |       |       |       |

How should I edit this SQL?

3
  • 1
    You have an extra comma after as form6. Commented Dec 8, 2014 at 18:20
  • @Barmar, its just a typo in stackoverflow :) Commented Dec 8, 2014 at 18:29
  • Then why haven't you corrected it? Commented Dec 8, 2014 at 20:32

1 Answer 1

5

You want conditional aggregation:

select user,
       sum(case when type = 'form1' then amount end) as form1,
       sum(case when type = 'form2' then amount end) as form2,
       sum(case when type = 'form3' then amount end) as form3,
       sum(case when type = 'form4' then amount end) as form4,
       sum(case when type = 'form5' then amount end) as form5,
       sum(case when type = 'form6' then amount end) as form6
from my_table
group by user;

Your error is occurring at least because the subqueries are returning more than one row. The group by in the subqueries pretty much means that they will return more than one row for each user.

Sign up to request clarification or add additional context in comments.

1 Comment

upvoted as this is correct, however for efficiency sake you may consider (a) making the CASE value rather than search, and (b) adding an ELSE 0 to each.

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.