2014-06-10 43 views
0

我正在做一個相對較小的查詢與子查詢,我想按降序對子查詢結果進行排序。但是在結果中,子查詢不按降序排列。無法看到一個原因ORDER BY不爲我工作...通過DESC SQL順序不起作用

我的查詢:

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 

我需要有一個DESC順序,因爲我想限制100,所以我得到的最高值100 。有人可以提出一種做法嗎?

+0

您是否想要每個客戶的前100名賭注?如果是的話你使用的是哪個數據庫? – Linger

+0

或..無論是6月1日還是6月2日,前100個投注金額值和/或頂級投注? – DRapp

+0

您的子查詢按降序排列。但是,您不能保證一旦兩個問題結合起來,結果將以相同的順序顯示。爲什麼不按日期和數量來排序呢? –

回答

1

排序方式不會像這樣繼續通過組。

這應該給你你在找什麼,而不是:

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 
  • 注:(改爲「First_June」,而不是開始與一些列名在多個SQL服務器的問題,和。 Oracle,MS SQL,MySql,Postgres等)
+0

請注意,arserbin3將您的第二個子查詢的別名從'First_June'更改爲'Second_June',並按第一個子查詢和第二個子查詢排序。 – Elias

+1

感謝您清除@Elias。我認爲這是基於日期範圍的拼寫錯誤,並對其進行了修正。 – arserbin3

+0

它幾乎可以正常工作,但有時候,訂單 – user3669523