表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
...所以基本上用realdate对total_cancels求和,对于每个realdate,我需要将canceldate分组2-12个月。
发布于 2018-08-13 03:39:54
使用聚合函数sum .but,这很奇怪,你显示输出取消日期列的方式就是这样。我想那是你的打字错误
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 发布于 2018-08-13 03:04:18
还没有测试过,但可能会有帮助?
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 我不太明白你在最后一篇专栏里想要什么。这只是根据每个total_cancels的realdate对product进行分组。
发布于 2018-08-15 18:57:26
似乎这个问题和我在这里回答的问题是一样的:join start_date and _end_date to another table and sum up
您要做的是将table_2连接到table_1,使用on条件,使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 https://stackoverflow.com/questions/51811747
复制相似问题