Sql 连接两个表以查看事件在一段时间内的效果

Sql 连接两个表以查看事件在一段时间内的效果,sql,Sql,我有一个警告表,其中包含一些条目,指示何时发送警告消息告知用户需要付款: Date user ========= ======= 1/2/2018 123 2/4/2018 123 3/15/2018 124 4/17/2018 125 etc. 然后我有一个记录表,通常记录用户何时付款 Date user amount country ========= ======= ====== ===== 2/1/2018 123

我有一个警告表,其中包含一些条目,指示何时发送警告消息告知用户需要付款:

     Date  user
========= =======
 1/2/2018    123
 2/4/2018    123
3/15/2018    124
4/17/2018    125
etc.
然后我有一个记录表,通常记录用户何时付款

     Date    user  amount  country
========= =======  ======  =====
 2/1/2018   123     50     UK
 3/1/2018   123     150    UK
 4/1/2018   125     300    US
 5/1/2018   124     100    CAN
etc.

我想知道每个国家/地区在警告前2天和警告后2天的平均付款之间的差异。

您可以运行
加入和聚合。这将使用标准SQL语法进行日期操作。数据库中的语法可能会有所不同:

select u.country,
       avg(case when p.date < w.date then p.amount end),
       avg(case when p.date >= w.date then p.amount end)
from warnings w join
     payments p
     on p.user = w.user and
        p.date >= w.date - interval '2 day' and
        p.date <= w.date + interval '2 day'
group by u.country;
选择美国国家/地区,
平均值(p.date=w.date然后p.amount end时的情况)
从警告到加入
付款p
在p.user=w.user和
p、 日期>=w.date-间隔“2天”和

p、 日期您可以运行加入和聚合。这将使用标准SQL语法进行日期操作。数据库中的语法可能会有所不同:

select u.country,
       avg(case when p.date < w.date then p.amount end),
       avg(case when p.date >= w.date then p.amount end)
from warnings w join
     payments p
     on p.user = w.user and
        p.date >= w.date - interval '2 day' and
        p.date <= w.date + interval '2 day'
group by u.country;
选择美国国家/地区,
平均值(p.date=w.date然后p.amount end时的情况)
从警告到加入
付款p
在p.user=w.user和
p、 日期>=w.date-间隔“2天”和

p、 日期和你的问题是什么?如果你想知道支付差异,我建议你要么查看数据,自己计算,要么写一个查询。用你正在使用的数据库标记你的问题。你的问题是什么?如果你想知道付款差额,我建议你要么查看数据,自己计算,要么写一个查询。用你正在使用的数据库标记你的问题。