如何使用 SQL 获取连续日期之间的最大差异
日期 1 | 日期 2 | 日期 3 | 日期 4 | LineCount | Month_Gap |
---|---|---|---|---|---|
2020-01-01 | 2019-10-01 | 2019-09-06 | 1 | ||
2020-01-01 | 2019-10-01 | 2019-09-13 | 2019-09-06 | 2 | 0 |
2020- 01-01 | 2019-10-01 | 2019-08-13 | 2019-09-06 | 2 | 1 |
如果 LineCount
为 1,则 Month_Gap
应为 (Date1 & Date1) 之间的最大月份差异。日期3)和(日期2&日期3)。 Date3 始终位于 Date1 和 Date2 之间。
在本例中,输出应为 (2020/01/01 - 2019/09/06) 和 (2019/10/01 - 2019/09/06) 之间的最大月份差异,即 3 个月:
Date 1 | Date 2 | 日期 3 | 日期 4 | LineCount | Month_Gap |
---|---|---|---|---|---|
2020-01-01 | 2019-10-01 | 2019-09-06 | 1 | 3 | |
2020-01-01 | 2019-10-01 | 2019-09-13 | 2019-09-06 | 2 | 0 |
2020-01-01 | 2019-10-01 | 2019-08-13 | 2019-09-06 | 2 | 1 |
我正在尝试这样的事情,但是不知道该怎么做 - CASE WHEN LineCount
= 1 THEN MAX(DATE_DIFF(.....),我猜这是行不通的。
Date 1 | Date 2 | Date 3 | Date 4 | LineCount | Month_Gap |
---|---|---|---|---|---|
2020-01-01 | 2019-10-01 | 2019-09-06 | 1 | ||
2020-01-01 | 2019-10-01 | 2019-09-13 | 2019-09-06 | 2 | 0 |
2020-01-01 | 2019-10-01 | 2019-08-13 | 2019-09-06 | 2 | 1 |
If the LineCount
is 1, then Month_Gap
should be the maximum month difference between (Date1 & Date3) and (Date2 & Date3). Date3 will always be in between Date1 and Date2.
In this Case, the output should be the max month difference between (2020/01/01 - 2019/09/06) and (2019/10/01 - 2019/09/06), which is 3 months:
Date 1 | Date 2 | Date 3 | Date 4 | LineCount | Month_Gap |
---|---|---|---|---|---|
2020-01-01 | 2019-10-01 | 2019-09-06 | 1 | 3 | |
2020-01-01 | 2019-10-01 | 2019-09-13 | 2019-09-06 | 2 | 0 |
2020-01-01 | 2019-10-01 | 2019-08-13 | 2019-09-06 | 2 | 1 |
I was trying something like this but not sure how to go about it -
CASE WHEN LineCount
= 1 THEN MAX(DATE_DIFF(.....), which won't work I guess.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用的模式是
这将简单地浏览您的列,找到最小和最大,并返回结果。
The pattern you should use is
This will simply look through your columns, find the least and greatest, and return the result.