今天早上我参与了这个查询。我浪费了我的2天。但没有得到好的解决方案。我有一个mysql查询
SELECT l.date_entered, n.date_entered, n.date_modified, n.name, n.parent_id
FROM `notes` AS n, leads AS l
WHERE n.parent_type = "Leads" && MONTH( l.date_entered ) =1 && YEAR( l.date_entered ) =2013 &&
n.parent_id = l.id
ORDER BY n.date_modified ASC
这给了我这个输出: -
date_entered date_entered date_modified name parent_id
2013-01-07 2013-01-07 2013-01-07 20:17:44 rahul 100
2013-01-07 2013-01-07 2013-01-07 22:27:38 rawat 101
2013-01-03 2013-01-07 2013-01-07 23:29:02 rohit 102
2013-01-03 2013-01-07 2013-01-07 23:33:55 mamta 100
2013-01-04 2013-01-08 2013-01-08 06:16:11 kiran 101
2013-01-07 2013-01-08 2013-01-08 07:10:10 ajay 100
现在,我试图通过匹配date-modified
来获得parent_id
差异,例如
我的输出将如下: -
date_entered date_entered date_modified name parent_id datediff
2013-01-07 2013-01-07 2013-01-07 20:17:44 rahul 100 0
2013-01-07 2013-01-07 2013-01-07 22:27:38 rawat 101 1
2013-01-03 2013-01-07 2013-01-07 23:29:02 rohit 102 not found
2013-01-03 2013-01-07 2013-01-07 23:33:55 mamta 100 skip due to previous match
2013-01-04 2013-01-08 2013-01-08 06:16:11 kiran 101 skip due to previous match
2013-01-07 2013-01-08 2013-01-08 07:10:10 ajay 100 skip due to previous match
答案 0 :(得分:0)
试试这个:
CREATE TABLE test as
(SELECT l.date_entered date1, n.date_entered date2, n.date_modified mod_date, n.name name, n.parent_id parentid
FROM `notes` AS n, leads AS l
WHERE n.parent_type = "Leads" && MONTH( l.date_entered ) =1 && YEAR( l.date_entered ) =2013 &&
n.parent_id = l.id);
select *,
case
when mod_date=b.min_date and count_parent_id>1 then cast( datediff(next_date,b.min_date) as char)
when count_parent_id=1 then 'not found'
else 'skip due to previous match'
end datediff
from
(SELECT Date1, Date2, mod_date, name, parentid
FROM test) as a
left join
(select min_date,next_date, count_parent_id, q1.parentid
from
(SELECT min(mod_date) min_date, count(parentid) count_parent_id, parentid
FROM test
group by parentid) q1
join
(SELECT min(mod_date) next_date, parentid
FROM test
where mod_date not in
(SELECT min(mod_date) min_date FROM test
group by parentid)
group by parentid
)q2
on q1.parentid=q2.parentid
) as b
on a.parentid=b.parentid
ORDER BY mod_date ASC ;
drop table test;
这很有效。查看SQL Fiddle