匹配列单元格与其他如果找到约会

时间:2013-02-20 12:22:08

标签: mysql sql sql-server query-builder

今天早上我参与了这个查询。我浪费了我的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个。这个日期在同一天修改,因此result = 0
  2. 下一个搜索是针对第5行中找到的101。此修改日期是前一个101之后的1天,因此结果= 1
  3. 下一次搜索是102,找不到,所以跳过它
  4. 下一次搜索是100,但已经找到了,所以跳过它
  5. 下一次搜索是101,但已经找到了,所以跳过它
  6. 下一次搜索是100,但已经找到了,所以跳过它
  7. 我的输出将如下: -

    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
    

1 个答案:

答案 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