English 中文(简体)
按组别分列的MySQL AVG(TIMESTAMPDIFF)
原标题:MySQL AVG(TIMESTAMPDIFF) with GROUP BY

我有两个表格<代码>用户(一个)和transaction (many),我需要从创建用户到进行第一次交易的平均时间。 使用<代码>AVG(TIMESTAMPDIFF)的Im 运行良好,但<代码>除外。 由<<>条/代码>分类的组别,在<条码>中,每个用户平均回报一次,而不是所有独特用户的单一平均数。 删除<代码> 按分类,我获得一个单一的平均数字,但考虑到用户的多项交易,而我只希望每个用户有一次(第一次)。

Here s my SQL:

SELECT AVG(TIMESTAMPDIFF(DAY, u.date_created, t.transaction_date)) AS average
FROM transaction t
LEFT JOIN user u ON u.id = t.user_id
WHERE t.user_id IS NOT NULL AND t.status = 1
GROUP BY t.user_id;

I d appreciate it if someone can help me return the average for unique users only. It s fine to break the query down into two, but the tables are large so returning lots of data and putting it back in is a no-go. Thanks in advance.

最佳回答
SELECT AVG(TIMESTAMPDIFF(DAY, S.date_created, S.transaction_date)) AS average 
FROM (
  SELECT u.date_created, t.transaction_date 
  FROM transaction t 
  INNER JOIN user u ON u.id = t.user_id 
  WHERE t.status = 1 
  GROUP BY t.user_id
  HAVING u.date_created = MIN(u.date_created)
) s

I replaced the LEFT JOIN with an INNER JOIN because I think that s what you want, but it s not 100% equivalant to your WHERE t.user_id IS NOT NULL.
Feel free to put the LEFT JOIN back if need be.

问题回答
select avg( TIMESTAMPDIFF(DAY, u.date_created, min_tdate) ) as average
from user u
inner join 
(select t.user_id, min(t.transaction_date) as min_tdate
 from transaction t
 where t.status=1;
 group by t.user_id
) as min_t
on u.id=min_t.user_id;




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签