MS Access查询 - 忽略'Order By'子句

时间:2011-04-13 23:02:05

标签: sql ms-access

SELECT u.UserLastName, u.UserID, SUM((Format(c.CallLength, 'h') * 60 *60)) as hourSeconds, SUM((Format(c.CallLength, 'n') * 60)) as minSeconds,
                SUM((Format(c.CallLength, 's'))) as seconds, COUNT(*) as 'callCount'
                FROM Calls AS c INNER JOIN User AS u ON c.UserID = u.UserID
                WHERE c.CallDate BETWEEN format(NOW(), 'yyyy-mm-dd 00:00:00') AND format(Now(), 'yyyy-mm-dd 23:59:59') AND u.UserLastName NOT IN ('Britt','Jason','System')
                GROUP BY u.UserID, u.UserLastName
                ORDER BY 'callCount' DESC;

我花了很多时间尝试使用“ORDER BY”子句对这个查询进行排序。什么是不正确的?它只是运行查询而没有错误,但似乎按u.UserID字段排序。无论我做什么,我都无法通过ORDER BY子句订购任何字段!

2 个答案:

答案 0 :(得分:2)

如果你的原始查询返回了你想要的数据而没有错误,唯一的问题是ORDER BY,我认为这个简单的改变是要走的路。

SELECT
    u.UserLastName,
    u.UserID,
    SUM((Format(c.CallLength, 'h') * 60 *60)) as hourSeconds,
    SUM((Format(c.CallLength, 'n') * 60)) as minSeconds,
    SUM((Format(c.CallLength, 's'))) as seconds,
    COUNT(*) as callCount
FROM Calls AS c INNER JOIN User AS u ON c.UserID = u.UserID
WHERE
    c.CallDate BETWEEN format(NOW(), 'yyyy-mm-dd 00:00:00')
    AND format(Now(), 'yyyy-mm-dd 23:59:59')
    AND u.UserLastName NOT IN ('Britt','Jason','System')
GROUP BY u.UserID, u.UserLastName
ORDER BY 6 DESC;

为字段(或表达式)指定别名时,不能在ORDER BY中使用该别名。但是,您可以通过字段列表中的序号位置来引用它。

答案 1 :(得分:1)

你不想使用字符串作为列名。

试试这个。

另外,如果我没记错的话,你不能订购和分组。所以一个子选择组,你可以订购结果......

Select * from (
    SELECT 
        u.UserLastName, 
        u.UserID, 
        SUM((Format(c.CallLength, 'h') * 60 *60)) as hourSeconds, 
        SUM((Format(c.CallLength, 'n') * 60)) as minSeconds,
        SUM(Format(c.CallLength, 's')) as seconds, 
        COUNT(*) as callCount 
    FROM Calls AS c 
    INNER JOIN User AS u ON c.UserID = u.UserID

    WHERE c.CallDate BETWEEN format(NOW(), 'yyyy-mm-dd 00:00:00') AND 
          format(Now(), 'yyyy-mm-dd 23:59:59') AND 
          u.UserLastName NOT IN ('Britt','Jason','System')
    GROUP BY u.UserID, u.UserLastName
)
ORDER BY callCount DESC;

如果您的列名不能使用,因为它是关键字或多个单词。试着在它周围放上方形支架。

[callCount]