Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table A it contains 4 columns as mentioned below
ID | SUBJECT  | MARKS1 | MARKS2 | 
1  | ENGLISH  | 10     | 20     |
2  | HINDI    | 20     | 30     |
3  | PHYSICS  | 10     | 10     |
4  | CHEMISTRY| 20     | 20     |
6  | BIOLOGY  | 10     | 10     |
7  | MATHS    | 5      | 25     |


I want to merge physics,chemistry, and biology in one row and wish to get result as

SUBJECT  | MARKS1 | MARKS2 |  TOTAL  |
ENGLISH  | 10     | 20     |  30     |
HINDI    | 20     | 30     |  50     |
SCIENCE  | 10     | 10     |  80     |
MATHS    | 5      | 25     |  30     |


Please help someone

What I have tried:

.................................... -----------------------------------------------------------------------------
Posted
Updated 14-Nov-19 8:24am
Comments
ZurdoDev 14-Nov-19 14:01pm    
SELECT *, (SELECT COUNT(*) FROM table WHERE subject = t1.subject) AS Total
FROM table t1

or join to a derived table
SELECT *, x.total
FROM table1 t1
INNER JOIN (
SELECT subject, COUNT(*) AS total
) x ON t1.subject = x.subject

1 solution

Seems simple enough - you just need a CASE statement to map the subject name, and a GROUP BY to group the rows with the same subject.

The only slightly tricky part is that you have to repeat the CASE statement in the GROUP BY clause.
SQL
SELECT
    CASE
        WHEN Subject In ('PHYSICS', 'CHEMISTRY', 'BIOLOGY') THEN 'SCIENCE'
        ELSE Subject
    END As Subject,
    Sum(Marks1) As Marks1,
    Sum(Marks2) As Marks2,
    Sum(Marks1 + Marks2) As Total
FROM
    YourTable
GROUP BY
    CASE
        WHEN Subject In ('PHYSICS', 'CHEMISTRY', 'BIOLOGY') THEN 'SCIENCE'
        ELSE Subject
    END
;
 
Share this answer
 
Comments
Maciej Los 14-Nov-19 16:24pm    
5ed!
Member 12245539 19-Nov-19 12:32pm    
5 star

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900