SQL:如何在INNER JOIN中使用DateDiff + ORDER BY

时间:2013-04-18 16:18:15

标签: sql sql-server inner-join datediff

这是我现有的SQL语句:

SELECT TOP 10 Users.FirstName + ' ' + Users.LastName AS Name,
              Feeds.LogType,
              Feeds.LogDesc,
              Feeds.Timestamp = DATEDIFF(MINUTE, Feeds.Timestamp, CURRENT_TIMESTAMP)
FROM Feeds
INNER JOIN Users ON Feeds.UserID = Users.UserID
ORDER BY Feeds.Timestamp DESC

我在第二行Incorrect syntax near '='.

上遇到错误

任何想法如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

尝试

SELECT TOP 10 Users.FirstName + ' ' + Users.LastName AS NAME
    ,Feeds.LogType
    ,Feeds.LogDesc
    ,DATEDIFF(MINUTE, Feeds.TIMESTAMP, CURRENT_TIMESTAMP)
FROM Feeds
INNER JOIN Users ON Feeds.UserID = Users.UserID
ORDER BY DATEDIFF(MINUTE, Feeds.TIMESTAMP, CURRENT_TIMESTAMP) DESC

答案 1 :(得分:1)

Feeds.Timestamp = DATEDIFF(MINUTE,Feeds.Timestamp,CURRENT_TIMESTAMP)应为

DATEDIFF(MINUTE, Feeds.Timestamp, CURRENT_TIMESTAMP) AS Timestamp 

答案 2 :(得分:1)

而不是尝试将别名改为,

SELECT TOP 10 Users.FirstName + ' ' + Users.LastName AS Name, Feeds.LogType,
    Feeds.LogDesc,
    DATEDIFF(MINUTE, Feeds.Timestamp, CURRENT_TIMESTAMP) [Timestamp]
FROM Feeds INNER JOIN Users ON Feeds.UserID = Users.UserID
ORDER BY Feeds.Timestamp DESC

答案 3 :(得分:1)

您可以使用“alias = value”的方式使用别名,但不应指定表名,所以

Timestamp = DATEDIFF(MINUTE, Feeds.Timestamp, CURRENT_TIMESTAMP)