TIMESTAMPDIFF适用于多种类型

时间:2014-09-07 05:58:58

标签: mysql sql

我有这个查询向我展示付款之间的平均时间差异

SELECT TIMESTAMPDIFF(SECOND, MIN(x.ts), MAX(x.ts) )/(COUNT(DISTINCT(x.ts)) -1) 
as average_minutes_between_paypal_orders 
from (
select p.created_at as ts 
from payment_tokens p 
where status='processed' and payment_method = 'paypal' 
order by created_at desc limit 100
) x

问题是,我希望它能够单独呈现其他方法之间的平均时间差异,例如' braintree'喜欢'其他'等等,我不想写几个问题。

有没有办法在1个查询中单独显示所有payment_methods?

1 个答案:

答案 0 :(得分:1)

使用CASE

进行所需计算的一种方法
SELECT 
TIMESTAMPDIFF(SECOND
              ,MIN(CASE WHEN x.payment_method = 'paypal' THEN x.ts END)
              ,MAX(CASE WHEN x.payment_method = 'paypal' THEN x.ts END) )
/(COUNT(DISTINCT(CASE WHEN x.payment_method = 'paypal' THEN x.ts END)) -1)  AS average_minutes_between_paypal_orders ,
TIMESTAMPDIFF(SECOND
              ,MIN(CASE WHEN x.payment_method = 'braintree' THEN x.ts END)
              ,MAX(CASE WHEN x.payment_method = 'braintree' THEN x.ts END) )
/(COUNT(DISTINCT(CASE WHEN x.payment_method = 'braintree' THEN x.ts END)) -1)  AS average_minutes_between_braintree_orders 
FROM (
SELECT p.created_at AS ts 
FROM payment_tokens p 
WHERE `status`='processed'
ORDER BY created_at DESC LIMIT 100
) `x`