MySQL - 跨多个表的算术

时间:2017-10-05 08:28:06

标签: mysql sql

假设我有两个表,12:55:38.242 |-INFO [Executor] Finished task 198.0 in stage 41.0 (TID 3012). 973 bytes result sent to driver 12:55:38.242 |-INFO [TaskSetManager] Starting task 199.0 in stage 41.0 (TID 3013, localhost, partition 199, PROCESS_LOCAL, 5553 bytes) 12:55:38.243 |-INFO [TaskSetManager] Finished task 198.0 in stage 41.0 (TID 3012) in 4 ms on localhost (199/200) 12:55:38.243 |-INFO [Executor] Running task 199.0 in stage 41.0 (TID 3013) 12:55:38.243 |-INFO [BlockManager] Found block rdd_93_199 locally 13:54:53.479 |-INFO [TaskSetManager] Finished task 76.0 in stage 11.0 (TID 69) in 29 ms on localhost (58/400) 13:54:53.480 |-INFO [Executor] Running task 78.0 in stage 11.0 (TID 70) 13:54:53.486 |-INFO [ShuffleBlockFetcherIterator] Getting 0 non-empty blocks out of 1 blocks 13:54:53.487 |-INFO [ShuffleBlockFetcherIterator] Started 0 remote fetches in 1 ms 13:54:53.495 |-INFO [Executor] Finished task 78.0 in stage 11.0 (TID 70). 3844 bytes result sent to driver People

Invoices

发票

firstname    postcode
Alex         2403
Peter        2357
Michael      3456

我想在People中添加一个名为income的列,显示每个人的总收入 - 我该如何实现?

我相信表格应该加入:

person       earned
Alex         12300
Alex         3556
Peter        1000
Alex         234
Michael      10000

但我当时不确定如何将所赚取的钱相加并将其分组到相应的收入中(我假设INNER JOIN Invoices ON People.firstname = Invoices.person 用于某处)。

5 个答案:

答案 0 :(得分:2)

显然非常依赖'firstname'和'person'作为连接,因为名称不是唯一的,但假设您使用的是任意数据示例:

select p.firstname, p.postcode, sum(i.earned) earnings from people p
inner join invoices i on p.firstname = i.person
group by i.person

给出

| *firstname* | *postcode* | *earnings* |
+-------------+------------+------------+
| Alex        | 2403       |   16090    |
| Michael     | 3456       |   10000    |
| Peter       | 2357       |   1000     |

也许不是最值得尊敬的资源,但此链接应有助于了解有关将GROUP BYSUM

一起使用的更多信息

https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php

答案 1 :(得分:1)

由于我无法弄清楚你的表是什么样的,我认为这段代码会有所帮助。

SELECT 
    a.firstname, 
    a.postcode, 
    SUM(b.earned)  
FROM 
    People a 
 LEFT OUTER JOIN 
    Invoices b 
ON 
    a.firstname = b.person  
GROUP BY 
    a.firstname

如果您可以添加有关表格的更多详细信息,那就太棒了。

答案 2 :(得分:0)

select p.firstname,sum(p.income)+sum(i.earned) from people p inner join 
invoice i on p.firstname = i.firstname where p.firstname =
'Alex' group by p.firstname;

此查询必须解决您的问题

答案 3 :(得分:0)

抱歉,SUM应该是。

SELECT
   firstname, 
   SUM(earned) AS earnings 
FROM People 
INNER JOIN Invoices 
  ON People.firstname = Invoices.person 
GROUP BY person

答案 4 :(得分:-2)

SELECT
   firstname, 
   count(earned) AS earnings 
FROM People 
INNER JOIN Invoices 
      ON People.firstname = Invoices.person 
GROUP BY person