sql-基于另一个表上的列的条件查询(日期范围)

时间:2020-08-19 03:48:38

标签: sql

我这里有2张桌子, 一个像查询表(会话),一个像交易表(事务)

session     
id  start_time          end_time
1   2020-08-13 06:47:18 2020-08-13 18:48:42
2   2020-08-13 18:49:21 2020-08-14 06:52:31
transaction 
id  payment_time
1   2020-08-13 06:49:18
2   2020-08-13 06:54:11
3   2020-08-14 06:44:00
4   2020-08-14 06:47:37

如何查询以获取下面的输出,它可以根据查找表值返回会话?

end_result      
id  payment_time          session
1   2020-08-13 06:49:18    1
2   2020-08-13 06:54:11    1
3   2020-08-14 06:44:00    2
4   2020-08-14 06:47:37    2

2 个答案:

答案 0 :(得分:0)

SELECT t.id AS id, t.payment_time, s.id AS session
FROM [session] s
INNER JOIN [transaction] t ON s.start_time <= t.payment_time AND s.end_time >= t.payment_time

答案 1 :(得分:0)

您可以尝试以下操作:

select T.id, T.payment_time, S.id
from [transaction] as T
inner join [session] as S on T.payment_time between S.start_time and S.end_time