SQL Server查询语法问题

时间:2011-07-07 10:01:22

标签: sql-server

你好,任何人都可以解释我的查询错误

SELECT    
     cDispatcherName AS Name, 
     cCallNature AS EmergencyCall, 
     COUNT(cCallNature) AS Total,
     (
        SELECT  
             COUNT(cCallNature)   
             FROM   CallInfo  
             WHERE (cCallNature ='Regular call') 
        GROUP BY cCallNature
     ) AS Expr1
FROM         CallInfo 
WHERE     (cCallNature = 'Emergency call')
GROUP BY cDispatcherName, cCallNature

给出了以下错误消息:

Errormsg::There was an error parsing the query. [ Token line number = 1,Token line offset = 93,Token in error = SELECT ]

2 个答案:

答案 0 :(得分:1)

它不完全清楚你从原始查询中得到什么,但你不能在SQL-CE中使用嵌套选择,除非它们返回一个集合(而不是标量值),所以改为尝试类似的东西;

    SELECT    
       CallInfo.cDispatcherName AS Name, 
       cCallNature AS EmergencyCall, 
       COUNT(cCallNature) AS Total,
       SUB.CNT AS RegularCalls
    FROM CallInfo
    LEFT JOIN (
       SELECT  
          cDispatcherName,
          COUNT(*) AS CNT
       FROM  CallInfo  
       WHERE cCallNature ='Regular call'
       GROUP BY cDispatcherName
    ) AS SUB ON CallInfo.cDispatcherName = SUB.cDispatcherName

    WHERE    cCallNature = 'Emergency call'
    GROUP BY CallInfo.cDispatcherName, CallInfo.cCallNature, SUB.CNT

答案 1 :(得分:0)

我认为这个查询可以用更好的方式编写,但我可以看到你没有指定的子查询的主要问题(DispatcherName)。

所以将子查询更改为以下

 (
        SELECT  
             COUNT(cCallNature)   
             FROM   CallInfo rcall  
             WHERE (cCallNature ='Regular call' and rcall.cDispatcherName =CallInfo.CallInfo ) 

     ) AS Expr1 

您也可以更改所有查询(但这取决于您的需求)

SELECT    
     cDispatcherName AS Name, 
     COUNT(cCallNature) AS EmergencyCallTotal,
     (
        SELECT  
             COUNT(cCallNature)   
             FROM   CallInfo rcall  
             WHERE (cCallNature ='Regular call' and rcall.cDispatcherName =CallInfo.CallInfo )
     ) AS RegularcallTotal
FROM         CallInfo 
WHERE     (cCallNature = 'Emergency call')
GROUP BY cDispatcherName