MSSQL 2005上MSSQL 2000的功能:GROUP BY CAST(...)麻烦

时间:2013-02-08 13:46:30

标签: sql sql-server sql-server-2005 casting group-by

我编写了一个统计表汇总表的函数。这个函数在MSSQL 2005下运行正常:

DECLARE
@start datetime, 
@final datetime, 

SET @start = '08.02.2012'
SET @final = '08.02.2013'

SELECT  
  CAST(
       FLOOR(ISNULL(col1,col2)/50) * 50 AS int
      ) AS [MyCol1],
  CAST(
       FLOOR(ISNULL(col1,col2)/50) * 50 AS int
      )+49 AS [MyCol2],    

 COUNT(*) AS [Anzahl],
CAST(AVG(col3) AS decimal(3,2)) AS [MyCol3]
FROM T
WHERE Time BETWEEN @start AND @final
GROUP BY 
  CAST(
     FLOOR(ISNULL(col1,col2)/50) * 50 AS INT 
  )
ORDER BY 1

现在我想在MSSQL 2000系统上使用此功能,但Group By区域似乎是错误的:

  

列在选择列表中无效,因为它不包含在聚合中   函数和GROUP BY子句。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

解决此问题的最简单方法是使用子查询:

SELECT [MyCol1], [MyCol1]+49 AS [MyCol2], COUNT(*) AS [Anzahl],
       CAST(AVG(col3) AS decimal(3,2)) AS [MyCol3]
FROM (select t.*, CAST(FLOOR(ISNULL(col1,col2)/50) * 50 AS INT) as [MyCol1]
      from T
     ) t
WHERE Time BETWEEN @start AND @final
GROUP BY [MyCol1]
ORDER BY 1

它还使查询更容易理解。