>,我写的答案是以类似的方式使用JOIN,但我认为你的方法更好。做得很好。恐怕我最近没有做Mysql,所以select中的变量对我来说是新的!谢谢@tpdi谢谢,我喜欢你使用MAX和COALESCE,我写的答案是以类似的方式使用JOIN,但我认为你的方法更
>,我写的答案是以类似的方式使用JOIN,但我认为你的方法更好。做得很好。恐怕我最近没有做Mysql,所以select中的变量对我来说是新的!谢谢@tpdi谢谢,我喜欢你使用MAX和COALESCE,我写的答案是以类似的方式使用JOIN,但我认为你的方法更,mysql,sql,date,datediff,Mysql,Sql,Date,Datediff,>,我写的答案是以类似的方式使用JOIN,但我认为你的方法更好。做得很好。恐怕我最近没有做Mysql,所以select中的变量对我来说是新的!谢谢@tpdi谢谢,我喜欢你使用MAX和COALESCE,我写的答案是以类似的方式使用JOIN,但我认为你的方法更好。 ID | Service Date | Date Difference | Indicator 1 | 1/22/2016 | 0 | 1 1 | 3/2
>,我写的答案是以类似的方式使用
JOIN
,但我认为你的方法更好。做得很好。恐怕我最近没有做Mysql,所以select中的变量对我来说是新的!谢谢@tpdi谢谢,我喜欢你使用MAX
和COALESCE
,我写的答案是以类似的方式使用JOIN
,但我认为你的方法更好。
ID | Service Date | Date Difference | Indicator
1 | 1/22/2016 | 0 | 1
1 | 3/26/2016 | 64 | 1
1 | 5/25/2016 | 60 | 0
1 | 9/15/2016 | 113 | 1
2 | 8/1/2016 | 0 | 1
3 | 1/26/2016 | 0 | 1
3 | 3/9/2016 | 43 | 0
3 | 4/30/2016 | 52 | 0
4 | 8/9/2016 | 0 | 1
5 | 11/19/2016 | 0 | 1
6 | 10/14/2016 | 0 | 1
7 | 1/31/2016 | 0 | 1
7 | 8/11/2016 | 193 | 1
create view id_and_date as
select id, service_date from your table;
create view id_and_date_and_prior as
select
a.id, a.service_date,
coalesce(
(select max(b.service_date) from id_and_date b
where b.id = a.id and b.service_date < a.service_date),
a.service_date)
as prior_date
from id_and_date a
select a.id, a.service_date, a.prior_date
date_diff(a.service_date, a.prior_date) as diff,
case when date_diff(a.service_date, a.prior_date) > 60
then 1 else 0 end
as indicator
from id_and_date_and_prior a
select t.*, datediff(prev_date, date) as diff,
(case when datediff(prev_date, date) < 60 then 0 else 1 end) as indicator
from (select t.*,
(case when @id = id
then (case when (@prev := @d) = NULL then 'never' -- intentional
when (@d := date) = NULL then 'never' -- intentional
else @prev
end)
when (@d := date) = NULL then 'never' -- intentional
else NULL
end) as prev_date
from t cross join
(select @id := -1, @d := '') params
order by id, date
) t
SELECT
c.id,
c.service_date,
@diff := DATEDIFF(c.service_date, c.prior_date) AS diff,
IF(@diff = 0 || @diff > 60, 1, 0) AS indicator
FROM (
SELECT
a.id,
a.service_date,
COALESCE(
(SELECT MAX(b.service_date)
FROM t AS b
WHERE b.id = a.id
AND b.service_date < a.service_date),
a.service_date
) AS prior_date
FROM t AS a
) AS c;
| id | service_date | diff | indicator |
| 1 | 2016-01-22 | 0 | 1 |
| 1 | 2016-03-26 | 64 | 1 |
| 1 | 2016-05-25 | 60 | 0 |
| 1 | 2016-09-15 | 113 | 1 |
| 2 | 2016-08-01 | 0 | 1 |
| 3 | 2016-01-26 | 0 | 1 |
| 3 | 2016-03-09 | 43 | 0 |
| 3 | 2016-04-30 | 52 | 0 |
| 4 | 2016-08-09 | 0 | 1 |
| 5 | 2016-11-19 | 0 | 1 |
| 6 | 2016-10-14 | 0 | 1 |
| 7 | 2016-01-31 | 0 | 1 |
| 7 | 2016-08-11 | 193 | 1 |