SQL 服务器交叉应用

SQL Server CROSS APPLY

我正在尝试将 CROSS APPLY 添加到此查询中。我以前从未做过,但一位同事建议这样做,这似乎很有道理。不过我遇到了语法错误。这是查询:

            SELECT
                i.IncidentID,
                i.AccountID,
                i.IncidentTypeID,
                i.IncidentStateID,
                i.CreateDate,
                i.LastModifyDate,
                i.LastModifyUser,
                (
                    SELECT
                        COUNT(*) 
                    FROM
                        Actions a
                    WHERE
                        a.IncidentID = i.IncidentID
                ) AS ActionCount
            CROSS APPLY
            (
                SELECT TOP 1
                    a.IncidentStateID,
                    a.LastModifyDate
                FROM Actions a
                WHERE a.IncidentID = i.IncidentID
                ORDER BY a.LastModifyDate DESC
            )
            FROM
                Incidents i
            WHERE i.IncidentTypeID = 44
            AND i.IncidentStateID = 7
            AND i.CreateDate >= ?
            AND i.CreateDate < ?

最终我需要获取最近发生事件的 "Action" 的 a.IncidentStateID 和 a.LastModifyDate。这就是为什么它按 DESC 排序并只选择前 1 个。任何人都看到语法问题。错误只是说 General error: 20018 Incorrect syntax near the keyword 'ORDER'.。如果我删除它,它会移动到另一段语法等等。

Apply 应该在 from 子句之后:

SELECT i.IncidentID, i.AccountID, i.IncidentTypeID,
        t.IncidentStateID, i.CreateDate, i.LastModifyDate, t.LastModifyUser,
        (SELECT COUNT(*) 
         FROM Actions a
         WHERE a.IncidentID = i.IncidentID
        ) AS ActionCount
FROM Incidents i CROSS APPLY( 
     SELECT TOP (1) a.IncidentStateID, a.LastModifyDate
     FROM Actions a
     WHERE a.IncidentID = i.IncidentID
     ORDER BY a.LastModifyDate DESC
     ) t
WHERE i.IncidentTypeID = 44 AND i.IncidentStateID = 7 AND 
      i.CreateDate >= ? AND i.CreateDate < ?;