[英]How to get Maximum Difference between Dates in a row using SQL
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).如果
LineCount
为 1,则Month_Gap
应该是 (Date1 & Date3) 和 (Date2 & Date3) 之间的最大月份差。 Date3 will always be in between Date1 and Date2. Date3 将始终在 Date1 和 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:在这种情况下,output 应该是 (2020/01/01 - 2019/09/06) 和 (2019/10/01 - 2019/09/06) 之间的最大月差,即 3 个月:
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.我正在尝试这样的事情,但不确定如何解决 go - CASE WHEN
LineCount
= 1 THEN MAX(DATE_DIFF(.....),我猜这是行不通的。
The pattern you should use is您应该使用的模式是
SELECT TIMESTAMPDIFF("MONTH", LEAST(date1,date2,date3,date4), GREATEST(date1,date2,date3,date4)) as `maximum_difference`;
This will simply look through your columns, find the least and greatest, and return the result.这将简单地查看您的列,找到最小和最大的列,然后返回结果。
SELECT
CASE WHEN LineCount = 1 THEN GREATEST(DATE_DIFF('month', Date3, Date1),
DATE_DIFF('month', Date3, Date2)) END AS Month_Gap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.