SQL group by和date interval

时间:2018-06-07 12:00:06

标签: sql

我有两张这样的桌子:

                  TABLE1 (SENDS)
 ------------------------------------------------
| ReceiptId | JobId |  SK  |       LogDate       |
|-----------|-------|------|---------------------|
| 0000001   | 67789 | 4151 | 6/4/2018 2:31:44 AM |
|-----------|-------|------|---------------------|
| 0000002   | 67789 | 4151 | 6/4/2018 8:25:50 AM |
|-----------|-------|------|---------------------|
| 0000003   | 67789 | 4151 | 6/4/2018 7:42:09 PM |
 ------------------------------------------------


           TABLE2 (CLICKS)
 ------------------------------------
| JobId |  SK  |       LogDate       |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 4:51:23 AM |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 5:32:52 AM |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 7:12:03 AM |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 5:14:37 PM |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 6:07:12 PM |
|-------|------|---------------------|
| 67789 | 4151 | 6/4/2018 9:46:52 PM |
 ------------------------------------

我需要创建一个SQL查询来从ReceiptId中提取TABLE1,以及(TABLE1.JobId = TABLE2.JobId& TABLE1.SK = TABLE2.SK)和{{1}的记录数量}介于TABLE2.LogDate和下一个最高TABLE1.LogDate之间。

所以这个例子的表结果是:

TABLE1.LogDate

非常感谢你。

1 个答案:

答案 0 :(得分:0)

您似乎想要将clicks加入sends,然后过滤logdate并使用GROUP BYcount()

但您的描述和所需的样本输出彼此不一致。

所以以下内容会得到您的描述所说的内容:

SELECT s.receiptid,
       s.jobid,
       s.sk,
       count(*)
       FROM sends s
            LEFT JOIN clicks c
                      ON c.jobid = s.jobid
                         AND c.sk = s.sk
       WHERE c.logdate >= s.logdate
             AND c.logdate <= (SELECT min(ss.logdate)
                                      FROM sends ss
                                      WHERE ss.logdate > s.logdate
                                            AND ss.jobid = s.jobid
                                            AND ss.sk = s.sk)
       GROUP BY s.receiptid,
                s.jobid,
                s.sk;

以下内容可获得您想要的样本输出:

SELECT s.receiptid,
       s.jobid,
       s.sk,
       count(*)
       FROM sends s
            LEFT JOIN clicks c
                      ON c.jobid = s.jobid
                         AND c.sk = s.sk
       WHERE c.logdate >= s.logdate
             AND c.logdate <= coalesce((SELECT min(ss.logdate)
                                               FROM sends ss
                                               WHERE ss.logdate > s.logdate
                                                     AND ss.jobid = s.jobid
                                                     AND ss.sk = s.sk),
                                       c.logdate)
       GROUP BY s.receiptid,
                s.jobid,
                s.sk;