将where子句添加到sub select时的语法错误

时间:2014-07-26 15:25:49

标签: sql-server

此查询运行正常但是,当我向除最后一个子选项之外的任何子选项添加where子句时,它会生成错误。下面提供的示例和错误。你能帮我解决这个语法错误吗?:

SELECT Getdate()                                            AS PullTime, 
       (SELECT Min(sqlagentstatus) 
        FROM   dbo.tracksqlagentstatus)                     AS SQLAgentStatus, 
       (SELECT Max(memorygrants) 
        FROM   dbo.trackmemorygrants)                       AS MemoryGrants, 
       (SELECT Avg(pagelifeexpectancy) 
        FROM   trackple)                                    AS PLE, 
       (SELECT Avg(freepages) 
        FROM   dbo.trackfreepages)                          AS FreePages, 
       (SELECT Avg(sqlprocesscpu) 
        FROM   dbo.trackcpu 
        WHERE  capturetime > Dateadd(minute, -5, Getdate()))AS CPU 

我需要为某些子查询添加一个where子句,但是当我执行如下所示时,它会生成错误。你知道我能做些什么来解决这个错误吗?

SELECT Getdate()                                             AS PullTime, 
       (SELECT Min(sqlagentstatus) 
        FROM   dbo.tracksqlagentstatus)                      AS SQLAgentStatus, 
       (SELECT Max(memorygrants) 
        FROM   dbo.trackmemorygrants)                        AS MemoryGrants, 
       (SELECT Avg(pagelifeexpectancy) 
        FROM   trackple)                                     AS PLE, 
       (SELECT Avg(freepages) 
        FROM   dbo.trackfreepages )                          AS FreePages
        WHERE  capturetime > Dateadd(minute, -5, Getdate()), 
       (SELECT Avg(sqlprocesscpu) 
        FROM   dbo.trackcpu 
        WHERE  capturetime > Dateadd(minute, -5, Getdate())) AS CPU 

收到的错误消息:

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ','.
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'as'.

这是Microsoft SQL Server数据库。

1 个答案:

答案 0 :(得分:1)

子查询的WHERE位于子查询之外。如果需要WHERE,还应该在子查询中使用别名。这应该有效:

SELECT Getdate()                                           AS PullTime, 
   (SELECT Min(sqlagentstatus) 
    FROM   dbo.tracksqlagentstatus)                        AS SQLAgentStatus 
   , 
   (SELECT Max(memorygrants) 
    FROM   dbo.trackmemorygrants)                          AS MemoryGrants, 
   (SELECT Avg(pagelifeexpectancy) 
    FROM   trackple)                                       AS PLE, 
   (SELECT Avg(freepages) 
    FROM   dbo.trackfreepages X 
    WHERE  X.capturetime > Dateadd(minute, -5, Getdate())) AS FreePages, 
   (SELECT Avg(sqlprocesscpu) 
    FROM   dbo.trackcpu 
    WHERE  capturetime > Dateadd(minute, -5, Getdate()))   AS CPU