Joris Portfolioris
Joris Portfolioris

Reputation: 138

get the average time for time from subscription until payment

I have two tables. The first is subscribers. Subscribers are also appointed to a category. The second table is payments that the subscribers made. I want to know what the average time is between the time of subscription and the FIRST payment of a subscriber (the can make multiple).

Here is a piece of SQL, but it doesn't do what I want just yet - although I have the feeling I'm close ;)

SELECT category,
AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, MIN(payments.timestamp)))
FROM subs
JOIN payments ON (payments.user_id = subs.user_id)
GROUP BY category

Now I get "Invalid use of group function" - because of the MIN function, so that ain't right. What do I have to do now? Thanks in advance!

Upvotes: 1

Views: 92

Answers (1)

dcp
dcp

Reputation: 55434

SELECT category,
AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, p.timestamp))
FROM subs
JOIN ( SELECT user_id
            , min(timestamp) timestamp
         FROM payments 
       GROUP BY user_id
     ) p
ON p.user_id = subs.user_id
GROUP BY category

If you needed to update another table with the results of this query, you could do something like this (not tested, so there may be syntax errors but hopefully you get the idea). I assume that another_table has category and avg_hrs_spent columns.

UPDATE another_table
   SET avg_hrs_spent =
     (
       SELECT a.avg_hrs_spent FROM
       (
         (SELECT category,
                 AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, p.timestamp)) avg_hrs_spent
            FROM subs
            JOIN ( SELECT user_id
                        , min(timestamp) timestamp
                     FROM payments 
                   GROUP BY user_id
               ) p
            ON p.user_id = subs.user_id
            GROUP BY category) a
       )
       WHERE a.category = another_table.category
     )

Upvotes: 2

Related Questions