查找 ID 匹配且日期在 X 天内的行
Find rows where ID matches and date is within X days
对 SQL 有点陌生,我 运行 遇到了一些项目问题。我有一个 table 这样的:
ID
subscription_ID
renewal_date
1
11
2022-01-01 00:00:00
2
11
2022-01-02 00:00:00
3
12
2022-01-01 00:00:00
4
12
2022-01-01 12:00:00
5
13
2022-01-01 12:00:00
6
13
2022-01-03 12:00:00
我的目标是 return 行,其中 subscription_ID 匹配并且 start_date 在或等于特定天数(小时数也可以)。例如,我想要 subscription_ID 匹配且 start_date 在或等于 1 天内的行,这样我从上面的 table 得到的结果将是:
ID
subscription_ID
renewal_date
1
11
2022-01-01 00:00:00
2
11
2022-01-02 00:00:00
3
12
2022-01-01 00:00:00
4
12
2022-01-01 12:00:00
如有任何帮助,我们将不胜感激 -- 谢谢!
如果我没理解错的话,您可能正在尝试类似的操作:
select t.*
from test_tbl t
join ( SELECT subscription_id
, MAX(diff) max_diff
FROM
( SELECT x.subscription_id
, DATEDIFF(MIN(y.start_date),x.start_date) diff
FROM test_tbl x
JOIN test_tbl y ON y.subscription_id = x.subscription_id
AND y.start_date > x.start_date
GROUP BY x.subscription_id , x.start_date
) z
GROUP BY subscription_id
) as t1 on t.subscription_id=t1.subscription_id
where t1.max_diff<=1;
Result:
id subscription_id start_date
1 11 2022-01-01 00:00:00
2 11 2022-01-02 00:00:00
3 12 2022-01-01 00:00:00
4 12 2022-01-01 12:00:00
子查询returns:
subscription_id max_diff
11 1
12 0
13 2
用于where条件。
对 SQL 有点陌生,我 运行 遇到了一些项目问题。我有一个 table 这样的:
ID | subscription_ID | renewal_date |
---|---|---|
1 | 11 | 2022-01-01 00:00:00 |
2 | 11 | 2022-01-02 00:00:00 |
3 | 12 | 2022-01-01 00:00:00 |
4 | 12 | 2022-01-01 12:00:00 |
5 | 13 | 2022-01-01 12:00:00 |
6 | 13 | 2022-01-03 12:00:00 |
我的目标是 return 行,其中 subscription_ID 匹配并且 start_date 在或等于特定天数(小时数也可以)。例如,我想要 subscription_ID 匹配且 start_date 在或等于 1 天内的行,这样我从上面的 table 得到的结果将是:
ID | subscription_ID | renewal_date |
---|---|---|
1 | 11 | 2022-01-01 00:00:00 |
2 | 11 | 2022-01-02 00:00:00 |
3 | 12 | 2022-01-01 00:00:00 |
4 | 12 | 2022-01-01 12:00:00 |
如有任何帮助,我们将不胜感激 -- 谢谢!
如果我没理解错的话,您可能正在尝试类似的操作:
select t.*
from test_tbl t
join ( SELECT subscription_id
, MAX(diff) max_diff
FROM
( SELECT x.subscription_id
, DATEDIFF(MIN(y.start_date),x.start_date) diff
FROM test_tbl x
JOIN test_tbl y ON y.subscription_id = x.subscription_id
AND y.start_date > x.start_date
GROUP BY x.subscription_id , x.start_date
) z
GROUP BY subscription_id
) as t1 on t.subscription_id=t1.subscription_id
where t1.max_diff<=1;
Result:
id subscription_id start_date 1 11 2022-01-01 00:00:00 2 11 2022-01-02 00:00:00 3 12 2022-01-01 00:00:00 4 12 2022-01-01 12:00:00
子查询returns:
subscription_id max_diff
11 1
12 0
13 2
用于where条件。