I have the following query that is using one table to find the revenue
column for a list of account numbers closest to either end of a date range, i.e. the row closest to the start of a date range, and the one closest to the end.
I've came up with the following but it only seems to work for the first account number and not any others after that.
SELECT a.acct_no,
b.revenue AS first_value, b.created_at AS first_date,
c.revenue AS second_value, c.created_at AS second_date
FROM `revenue_figures` a
LEFT JOIN (
SELECT `acct_no`, `revenue`, `created_at`
FROM `revenue_figures`
WHERE `created_at` BETWEEN '2017-02-28 00:00:00' AND '2017-03-31 23:59:59'
AND `acct_no` IN ('A123', 'A124')
GROUP BY `acct_no`, `revenue`, `created_at`
ORDER BY `created_at` ASC
LIMIT 1
) b ON a.acct_no = b.acct_no
LEFT JOIN (
SELECT `acct_no`, `revenue`, `created_at`
FROM `revenue_figures`
WHERE `created_at` BETWEEN '2017-02-28 00:00:00' AND '2017-03-31 23:59:59'
AND `acct_no` IN ('A123', 'A124')
GROUP BY `acct_no`, `revenue`, `created_at`
ORDER BY `created_at` DESC
LIMIT 1
) c ON a.acct_no = c.acct_no
WHERE a.`created_at` BETWEEN '2017-02-28 00:00:00' AND '2017-03-31
23:59:59'
AND a.`acct_no` IN ('A123', 'A124')
GROUP BY a.acct_no, first_value, first_date, second_value, second_date
This produces the following, but there are figures in the table for the A124
account number:
acct_no first_value first_date second_value second_date
A123 8990.00 2017-02-28 7364.80 2017-03-31 01:00:00
A124 NULL NULL NULL NULL
I think there is a fundamental flaw with the query as I noticed that if I run it a few times, I can generate different results, such as:
acct_no first_value first_date second_value second_date
A123 8990.00 2017-02-28 NULL NULL
A124 NULL NULL 28361.76 2017-03-31 01:00:00
Table Structure
id, acct_no, revenue, created_at
Example Data
1, A123, 8990.00, 2017-02-28 01:00:00
2, A123, 7364.80, 2017-03-31 01:00:00
3, A124, 17324.12, 2017-02-28 01:00:00
4, A124, 28361.76, 2017-03-31 01:00:00