如何在SQL中找到正负最近的日期并选择所需的列

发布于 2025-01-16 02:56:12 字数 1004 浏览 3 评论 0原文

我想选择 PatID、Indx_date、Ecogvalue、Ecogdate。 Ecogdate 应更接近 Indx_date。 Ecogdate 可以是 Indx_date 之前 30 天,也可以是 Indx_date 之后 7 天。 输入:

| PatID | Indx_date | Ecogvalue | Ecogdate   |  
| 1     | 2020-07-22| 0         | 2020-07-28 |   
| 1     | 2020-07-22| 1         | 2019-05-13 |  
| 1     | 2020-07-22| 1         | 2019-05-20 |

预期输出:

| PatID | Indx_date | Ecogvalue | Ecogdate   |  
| 1     | 2020-07-22| 1         | 2019-05-13 |

我尝试找出日期之间的差异并使用abs()转换为正数。我可以找到最近的日期,但无法获得所需的列。

| PatID | Indx_date | Ecogvalue | Ecogdate   | diff | pos_diff |  
| 1     | 2020-07-22| 0         | 2020-07-28 | 6    | 6        |  
| 1     | 2020-07-22| 1         | 2019-05-13 | -3   | 3        |  
| 1     | 2020-07-22| 1         | 2019-05-20 | 4    | 4        |

我想要这个作为输出

| PatID | Indx_date | Ecogvalue | Ecogdate   | diff | pos_diff |  
| 1     | 2020-07-22| 1         | 2019-05-13 | -3   | 3        |

I want to select PatID, Indx_date, Ecogvalue, Ecogdate. The Ecogdate should be nearer to the Indx_date. Ecogdate can be 30 days prior to Indx_date and 7days after Indx_date.
INPUT:

| PatID | Indx_date | Ecogvalue | Ecogdate   |  
| 1     | 2020-07-22| 0         | 2020-07-28 |   
| 1     | 2020-07-22| 1         | 2019-05-13 |  
| 1     | 2020-07-22| 1         | 2019-05-20 |

expected output:

| PatID | Indx_date | Ecogvalue | Ecogdate   |  
| 1     | 2020-07-22| 1         | 2019-05-13 |

I tried to find the difference btw the dates and converted to positive numbers using abs(). I can find the nearest date but can not get the required columns.

| PatID | Indx_date | Ecogvalue | Ecogdate   | diff | pos_diff |  
| 1     | 2020-07-22| 0         | 2020-07-28 | 6    | 6        |  
| 1     | 2020-07-22| 1         | 2019-05-13 | -3   | 3        |  
| 1     | 2020-07-22| 1         | 2019-05-20 | 4    | 4        |

I want this as output

| PatID | Indx_date | Ecogvalue | Ecogdate   | diff | pos_diff |  
| 1     | 2020-07-22| 1         | 2019-05-13 | -3   | 3        |

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文