在sql中选择条件的行

问题描述:

visid,custid和value的每个concactentation都可能具有“detail”和“confirm”或仅“detail”。 如果它只有“细节”,这行不应该被检索,否则我一定要找到日期时间 之间的区别时visid,客户ID和值的组合,同时拥有“详细信息”和“确认”在sql中选择条件的行

visid  custid value  datetime    value1 
123  456  11  2017-03-01 12:34:11  Detail 
123  456  11  2017-03-01 12:36:11  confirm 
567  342  56  2017-03-01 12:45:11  Detail 
567  342  56  2017-03-01 12:46:11  confirm 
411  124  78  2017-03-01 12:34:11  Detail 

Output: 
visid  custid value  datetime    
123  456  11  00:02:00 (12:36:11 - 12:34:11) 
567  342  56  00:01:00 (12:46:11 - 12:45:11) 

注意:由于411,124和78的最后一行没有确认,所以该行必须被删除。

查询我想:

select visid, custid, value, concat(visid, custid, value) as session, datetime 
    from table1 
    where datetime between "2017-05-01 00:00:00" and "2017-05-02 00:00:00" 
    and value1 in ('Detail','Confirm') 
+1

用您正在使用的数据库标记您的问题。 –

datetime功能是特定的数据库。在你的情况下,自我加入是一种简单的方法:

select td.visid, fd.custid, td.value, concat(visid, custid, value) as session, 
     (tc.datetime - td.datetime) as diff 
from table1 td join 
    table1 tc 
    on td.visid = tc.visid and td.custid = tc.custid and td.value = tc.value and 
     td.value1 = 'Detail' and tc.value1 = 'Confirm'; 

这使用减法的差异。确切的功能取决于数据库。