Kunal Batra Kunal Batra - 2 months ago 7
MySQL Question

How to execute join query with another group by select statement


I am executing two queries first for inner join to get data from table
and second group by query to get the sum.

But is there any way to execute two queries in one query?

First query:

SELECT e.name,Value,address FROM table1 e JOIN table2 p ON p.name = e.name;



+--------+---------+------+----+
| name | Value | address |
+--------+---------+------+----+
| name1 | 124 | address1 |
| name2 | 12 | address2 |
| name3 | 123 | address3 |
| name2 | 15 | address2 |
+-------------+---------+------+



Second query :

SELECT name
, SUM(Value) Total
FROM table1
GROUP BY name;



+-------------+-------+
| name | Total |
+-------------+-------+
| name3 | 123 |
| name2 | 27 |
| name1 | 124 |
+-------------+-------+



and what I want is a sum column against every name


+-------------+------------+
| name | sum | address |
+-------------+------------+
| name1 | 124 | address1 |
| name2 | 12 | address2 |
| name3 | 123 | address3 |
+-------------+------------+

Answer

try to use

SELECT donation_entry.Person_name,B.Total,Receipt,Date,month,Year,print_year,Valu e,address 
FROM donation_entry 
JOIN profile ON donation_entry.Person_name = profile.Person_name
JOIN (select Person_name,sum(Value) as Total from donation_entry group by Person_name)B on B.Person_name=donation_entry;