0

今天早上我参与了这个查询。我浪费了我的 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例如

  1. 从 100 开始,搜索在第 4 行返回另一个 100。此日期在同一天修改,因此结果 = 0
  2. 下一个搜索是在第 5 行找到的 101。这个修改日期是前一个 101 之后的 1 天,所以结果 = 1
  3. 下一个搜索是102,没有找到,所以跳过
  4. 下一个搜索是100,但是这个已经找到了,所以跳过它
  5. 下一个搜索是101,但是这个已经找到了,所以跳过
  6. 下一个搜索是100,但是这个已经找到了,所以跳过它

我的输出将是: -

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
4

1 回答 1

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 小提琴

于 2013-02-20T12:48:59.407 回答