Reputation: 69
I am doing a relatively small query with a sub query where I want to sort the sub query results in descending order. But in the result the sub query are not ordered in a descending order. Cannot see a reason why the ORDER BY does not work for me...
my query:
select
customers.id,
customers.Name,
customers.Surname,
(select ifnull(sum(bets.amount),0)
from bets
where customers.id=bets.customerId
and bets.date >'2014-06-01'
and bets.date <'2014-06-02'
order by bets.amount DESC
) as '1st_June',
(select ifnull(sum(bets.amount),0)
from bets
where customers.id=bets.customerId
and bets.date >'2014-06-02'
and bets.date <'2014-06-03'
order by bets.amount DESC
) as '1st_June',
from customers
group by customers.id
I need to have a DESC order because I want to limit 100 so i get the top 100 values. Could someone suggest a way of doing this...?
Upvotes: 0
Views: 8076
Reputation: 6148
Order By does not carry over past the group by like that.
This should give you what you're looking for instead:
SELECT customers.id
,customers.Name
,customers.Surname
,(
SELECT ifnull(sum(bets.amount), 0)
FROM bets
WHERE customers.id = bets.customerId
AND bets.date > '2014-06-01'
AND bets.date < '2014-06-02'
) AS First_June
,(
SELECT ifnull(sum(bets.amount), 0)
FROM bets
WHERE customers.id = bets.customerId
AND bets.date > '2014-06-02'
AND bets.date < '2014-06-03'
) AS Second_June
FROM customers
GROUP BY customers.id
ORDER BY First_June DESC
,Second_June DESC
LIMIT 100
Upvotes: 2