2013-01-17 63 views
0

我嘗試使用下面的函數,按小時計算的訂單數量:ORDER BY子句不能與集團合作,通過

SELECT 
    COUNT(id) total, 
    DATENAME(HOUR, purchased_on) label, 
    site 
FROM dhs.dbo.orders 
WHERE purchased_on >= '01/16/2013' 
GROUP BY DATENAME(HOUR, purchased_on), site 
ORDER BY label DESC 

我越來越即使我現在用的是下面的結果和ORDER BY子句應該把它們從最高標號開始依次排列:

total label site 
2   9  AMAZON 
1   9  DHS 
2   8  AMAZON 
1   7  AMAZON 
1   6  AMAZON 
1   4  AMAZON 
1   12 AMAZON 
3   11 AMAZON 
1   10 AMAZON 
1   10 DHS 

爲什麼不按順序工作?

回答

3

DATENAME返回一個VARCHAR

DATEPART替換爲:

SELECT COUNT(id) total, 
     DATEPART(HOUR, purchased_on) label, 
     site 
FROM dhs.dbo.orders 
WHERE purchased_on >= '01/16/2013' 
GROUP BY 
     DATEPART(HOUR, purchased_on), site 
ORDER BY 
     label DESC 
+0

你是對的,只是檢查DATENAME的返回值和一個varchar。謝謝你的幫助。 – Mike