Im having trouble getting my head round subqueries in Mysql. Fairly simple ones are ok, and most tutorials I find rarely go beyond the typical:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
What I am trying to pull out of my database is the following (I'll try my best to explain this without any background on our db):
Retrieve list of customers belonging to particular rep and total amount spent in last month (in one column) and amount spent in month to date, in other column.
As results, this would look roughly as follows:
ID | NAME | PREV MONTH | CUR MONTH
1 | foobar | £2300 | £1200
2 | barfoo | £1240 | £500
Query I am using to get the first part of the data is the following:
SELECT c.id,c.name, SUM(co.invoicetotal) as total
FROM customers as c
JOIN customerorders as co on co.customer_id = c.id
WHERE c.salesrep_id = 24
AND co.orderdate BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
GROUP by c.id
order by total desc
The DATE_SUB can be replaced by actual dates, as php variables will be going here eventually. As an example this just gives me valid data.
This gives me, for example:
ID | NAME | TOTAL
1 | foobar | £2300
2 | barfoo | £1240
So, ideally, my subquery would be this exact same query, but with the dates changed. I keep getting a #1242 - Subquery returns more than 1 row
error.
Any suggestions or advice please?
Thanks in advance. Rob