gpt4 book ai didi

SQL(sqlite)比较由另一个重复行分组的行的总和

转载 作者:行者123 更新时间:2023-12-03 17:57:27 25 4
gpt4 key购买 nike

我有一张像这样的 table :

|------------------------|  
|day name trees_planted|
|------------------------|
|1 | alice | 3 |
|2 | alice | 4 |
|1 | bob | 2 |
|2 | bob | 4 |
|------------------------|

我正在使用 SELECT name, SUM(trees_planted) FROM year2016 GROUP BY name要得到:
name  | trees_planted  
alice | 7
bob | 6

但是我有另一个 2015 年的表,我想将结果与前一年进行比较,例如,如果 Alice 在 2016 年种植的树比 2015 年多,我会得到这样的结果:
name  | tree_difference  
alice | -2 (if previous year she planted 5 trees, 5 -7 = -2)
bob | 0 (planted the same number of trees last year)

最佳答案

您可以使用子查询来获取 2016 年和 2015 年的记录,但否定 2016 年的值。然后像您已经做过的那样分组和求和:

SELECT    name, 
SUM(trees_planted) AS tree_difference
FROM (SELECT name, trees_planted
FROM year2015
UNION ALL
SELECT name, -trees_planted
FROM year2016
) AS years
GROUP BY name

这也适用于仅在两年中的一年中给出数字的情况。

关于SQL(sqlite)比较由另一个重复行分组的行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com