如何通过select语句与另一个组执行连接查询

时间:2016-10-08 07:52:08

标签: mysql sql-server join

  

我首先为内部联接执行两个查询以从表中获取数据   第二组通过查询获得总和。

     

但有没有办法在一个查询中执行两个查询?

     

首先查询:

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  | 
+-------------+---------+------+
  

第二次查询:

SELECT name
     , SUM(Value) Total 
  FROM table1 
 GROUP BY name;
+-------------+-------+
| name        | Total |
+-------------+-------+
| name3       |   123 |
| name2       |    27 |
| name1       |   124 |
+-------------+-------+
  

我想要的是一个针对每个名字的总和列

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

2 个答案:

答案 0 :(得分:1)

尝试使用

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;

答案 1 :(得分:0)

在第一个查询中将SUM汇总添加到value列并添加 Group by

中的非汇总
SELECT table1.name,
           Sum(Value),
           address
    FROM   table1
           JOIN table2
             ON table1.name = table2.name
    GROUP  BY table1.name,
              address 

name

中考虑table2是唯一的