0

I have two tables as follows:

table1

id | fullname | gender | level
------------------------------
1  | Jerry    | Male   | Year 1
2  | Jen      | Female | Year 1
3  | Tom      | Male   | Year 2
4  | Natasha  | Female | Year 2

table2

level | male | female
----------------------
      |      |
      |      |

What I want to do is to INSERT the total no. of male and total no. of female from table1 into table2 group by the level.

The expected result supposed to look like the following table:

level  | male | female
---------------------
Year 1 |  1   |  1
Year 2 |  1   |  1

I've tried the following code:

INSERT INTO table2 (level, male, female)
SELECT level,
       SUM(gender = 'Male') male,
       SUM(gender = 'Female') female,
FROM table1
GROUP BY level

The above code I got it from one of the question asked here as it seemed to have the same problems as mine BUT when I run the code, it doesn't give me anything.

Is the problem from the tables itself? Or is it from the code?

3
  • THere is a comma after female. I consider this a typographic error and vote to close such questions. Commented Nov 3, 2014 at 18:35
  • @GordonLinoff I just realised about that. Thank you but it still doesn't work :( Commented Nov 3, 2014 at 18:40
  • It works. The order of the column were wrong. Sorry for the inconvenient. Thank you again :)) Commented Nov 3, 2014 at 18:58

1 Answer 1

1

This will solve your problem.

INSERT INTO table2 (level,male,female) 
SELECT level, 
SUM(CASE WHEN `gender` = 'Male' THEN 1 ELSE 0 END) AS male, 
SUM(CASE WHEN `gender` = 'female' THEN 1 ELSE 0 END) AS female 
FROM `table1` GROUP BY level
Sign up to request clarification or add additional context in comments.

5 Comments

Hey. thanks for the response. But I have another problem. I want to update the whole table by replacing INSERT INTO to REPLACE INTO but instead of replacing the contains of the table, it keeps on adding them. I've tried a lot of possibility but it's just gave me the result.
*gace me the same result
There's another problem appear. I can update the table but it couldn't insert any new records :(
@SujiOK, Without looking at your statement and schema of your table, i can not help you much. But i should caution you as you are using REPLACE INTO. It is not always best solution. If handled inappropriately, it can do a lot of damage. Read comments here. Saying that, I think, You need to make column 'level' in table2 as primary.
I have solve that problem by just taking the value straight from table 1. I just didn't think of that way earlier. I'm so slow at that. Anyway, thank you from response. I appreciate it so much :))

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.