0

In my table in MYSQL have category 1-12 and under category question 001-300, a have create sum from category 6+7+8+9+10 example category question correct 1 1 3 1 2 9 2 1 8 6 1 2 7 1 9 12 10 3 result category question correct 1 1 3 1 2 9 2 1 8 6+7 1 11 12 10 3

How to do it?

3
  • 1
    Your question doesn't really make sense. Where does the second line for "12" come from? Are you trying to modify the data or just query it? Commented Nov 18, 2015 at 12:26
  • Sorry, error in copy. Commented Nov 18, 2015 at 12:38
  • This kind of problem can be indicative of poor design. Commented Nov 18, 2015 at 12:55

2 Answers 2

1

You can use UNION to achieve what you want.

Sample output :enter image description here

Here is SQLFiddle Demo

  SELECT *
  FROM table_name WHERE `category`<6
  UNION

  SELECT (GROUP_CONCAT(`category` SEPARATOR '+')) AS category,
          (GROUP_CONCAT(DISTINCT `question` SEPARATOR '+')) AS question,
          (SUM(`correct`)) AS correct
  FROM table_name WHERE category BETWEEN 6 AND 10

  UNION

  SELECT *
  FROM table_name WHERE `category`>10

Hope this helps.

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

Comments

1

Just use group by with a case statement:

select (case when min(category) = max(category) then min(category)
             else group_concat(category order by category separator '+')
        end) as category,
       question, sum(correct) as correct
from mytable
group by (case when category in (6, 7, 8, 9, 10) then -1 else category end),
         question;

Actually, this can be simplified to:

select group_concat(category order by category separator '+') as category,
       question, sum(correct) as correct
from mytable
group by (case when category in (6, 7, 8, 9, 10) then -1 else category end),
         question;

Comments

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.