I can't work out how to do this in MySQL:
I have tables transactions and clients.
I want to group the sales for each clients first month into ClientMonth 0, 1, 2 so I can look at how sales tend to change over time for all clients as a group (regardless of when they began dealing with us)
I've been trying to do this with
DATEDIFF(client_firstdeal_date.firstdeal_date, MAX(dealdate)+1) AS TenureDays, DATEDIFF(MAX(dealdate)+1, CURDATE()) AS FallowDays
and wanting to group by TenureDays but I'm not getting sensible results and I'm sure I'm misusing the mix of DATEDIFF, MAX and GROUP BY.
EDIT: Reading what I'd written and thinking more about what Adi said below, I went to the the start thinking, 'what exactly do I want (at each stage)'
Anyway, I solved my problem with the below (I really was making it too hard for myself):
SELECT
c.division,
SUM(t.profitgbp),
COUNT(ts.id),
SUM(t.profitgbp)/COUNT(t.id) AS AverageProfPerTrans,
ROUND(DATEDIFF(t.transdate,ft.firsttrans_date)/30,0) AS ClientMonth
FROM transactions t
LEFT OUTER JOIN client_firsttrans_date ft
ON t.accountno=ft.accountno
JOIN clients c
ON c.accountno=t.accountno
GROUP BY
ClientMonth,
division
client_firsttrans_date is a view that I guess makes this easier to
I'm pleased with the results, as it outputs to a nice chart showing how transaction numbers drop of over the life of a client, with some divisions being more lossy than others.
Thanks to everyone who took the time to look at my question.