按条款订购不与GROUP BY合作

时间:2013-01-17 17:34:43

标签: sql sql-server-2008 group-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  

为什么不按工作顺序?

1 个答案:

答案 0 :(得分: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