Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

presto - join start_date and _end_date to another table and sum up

table 1 table columns are:

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

table 2

realdate  cancel_start_date    cancel_end_date
6/1/2017    6/1/2016           4/1/2017
6/2/2017    6/2/2016           4/2/2017
6/3/2017    6/3/2016           4/3/2017
.
.
.

so table1.cancel_date between t2.cancel_start_date and t2.cancel_end_date, how can I join these two tables?

what I want to get

product    realdate      total_cancels   cancel_date between start_date and end_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
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to do is join table_2 to the table_1, using the on condition such that table_1. cancel_date is between table_2.cancel_start_date and table_2.cancel_end_date. But first we need to use the DATE_PARSE function to make the dates comparable. Finally just sum up the values.

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...