如何在SQL中找到正负最近的日期并选择所需的列
我想选择 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论