mysql - SQL 查询 :- Difference prices of same month with same year with different tables , 如果不只是显示零

标签 mysql sql

有两个不同的表,只需要减去同年同月之间的价格,如果没有数据就显示该特定月份和年份的零。现在,它只是逐行减去,而不考虑月份和年份。

Table 1                     Table2
Price   tran_date           Price       post_date
60      2018-01-01  30          2018-01-15
40      2018-02-08  30          2018-02-02
50      2018-12-28  30          2018-11-01
40      2019-03-01  10          2019-01-08
80      2019-04-11  60          2019-04-29
                    40          2019-10-01

Expected Answer:
Sum(price).        Year
30          January 2018
10          February    2018
30          November 2018
50          December 2018
-10         January 2019
40          March 2019
20          April 2019.
40          October 2019

Actual Answer:
Sum(Price)      Year
30          January 2018
10          February 2018
10          December 2018
30          March 2019
20          April 2019
-40         October 2019

表1的SQL查询

Select sum(price) from table1 where date(tran_date) 
between ‘2018-01-01’ and ‘2019-12-31’ 
group by month(tran_date),year(tran_date)

表2的SQL查询

Select sum(price) from table2 where date(post_date) 
between ‘2018-01-01’ and ‘2019-12-31’ 
group by month(post_date),year(post_date)

表1的第一行不应该与表2的第一行相减,而应该是同年同月相减。如果没有数据,则仅显示该特定月份和年份的零。

请帮忙。提前致谢。

最佳答案

似乎你想要绝对差异,尝试添加abs()

样本

select date_year, date_month,
       abs(sum(price))
from ((select date_year, date_month, price from 
    (values (60, '2018', '01'),  
        (40, '2018', '02'),  
        (50, '2018', '12'),  
        (40, '2019', '03'),  
        (80, '2019', '04')  ) table1 (price, date_year, date_month)
      ) union all
      (select date_year, date_month, - price from (
    values (30, '2018', '01'),
        (30, '2018', '02'),
        (30, '2018', '11'),
        (10, '2019', '01'),
        (60, '2019', '04'),
        (40, '2019', '10')
      ) table2 (price, date_year, date_month)
      )
     ) t
group by date_year, date_month
order by date_year, date_month

看 fiddle

https://www.db-fiddle.com/f/qVQYB2KXSTbJNEkSH1oGuG/0

关于mysql - SQL 查询 :- Difference prices of same month with same year with different tables , 如果不只是显示零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266922/

相关文章:

mysql:如何避免两次保存相同的数据?

MySQL : Set user variable from result of query with multiple values

MySQL 在一个查询中对不同表进行多次计数

sql - 在 SQL 编码中可以在 TRIGGER 中使用 DEFERRABLE 吗? DEFERRABLE 是如何工作的?

php - 将数字添加到自身并仅打印最后一个值的更好方法

java - 如何在Excel中动态汇总工作时间?

php - 显示 SQL 详细信息时出错

sql - 数据透视表中的文本值?

mysql - 在 mysql 中的表中存储 200 个字段的最佳和有效方法

MySQL - 单个查询中的两个相关加权平均值