表1的表列为:
cancel_date product total_cancels
6/1/2017 a 100
6/1/2017 b 40
6/2/2017 b 10
6/3/2017 b 20
.
.
.
6/1/2018 a 40
6/1/2018 b 10
表2
realdate
6/1/2017
6/2/2017
6/3/2017
.
.
.
6/1/2018
我想得到什么
product realdate total_cancels cancel_date
a 6/1/2017 100000 6/1/2016-4/30/2017
b 6/1/2017 8000 6/1/2016-4/30/2017
a 6/2/2017 100000 6/2/2016-5/1/2017
b 6/2/2017 8000 6/2/2016-5/1/2017
...
因此,基本上,可以按实际总和对total_cancels进行汇总,对于每个实际,我需要将取消日期分组为2-12个月。
答案 0 :(得分:0)
还没有对此进行测试,但可能会有所帮助吗?
select t1.product, t2.realdate, sum(t1.total_cancels)
from t1 join t2 on t1.cancel_date=t2.realdate
group by t1.product, t2.realdate
我不确定我在上一栏中理解您想要什么。这只是将{{1}中的total_cancels
按realdate
分组。
答案 1 :(得分:0)
使用聚合函数sum
。但是您显示输出的奇怪方式取消了date列。我认为这是您的输入错误
select t1.product, t2.realdate, sum(t1.total_cancels) as total_cancels
from Table1 t1 inner join Table2 t2 on date(t1.cancel_date)=date(t2.realdate)
group by t1.product, t2.realdate
答案 2 :(得分:0)
似乎这个问题与我在这里回答的问题相同: join start_date and _end_date to another table and sum up
您要执行的操作是使用table_1这样的on条件将table_2连接到table_1。 cancel_date在table_2.cancel_start_date和table_2.cancel_end_date之间。但是首先我们需要使用DATE_PARSE函数使日期具有可比性。最后,对这些值进行汇总。
SELECT
table_1.product,
table_2.realdate,
SUM(total_cancels) AS total_cancels,
CONCAT(table_2.cancel_start_date, '-', table_2.cancel_end_date) as start_to_end
FROM table_1
JOIN table_2
WHERE DATE_PARSE(table_1. cancel_date, '%m/%d/%Y')
BETWEEN DATE_PARSE(table_2.cancel_start_date, '%m/%d/%Y')
AND DATE_PARSE(table_2.cancel_end_date, '%m/%d/%Y')
GROUP BY 1, 2, 4