1

我编写了一个函数,可以统计地汇总表的记录。此函数在 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 region 似乎是错误的:

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

有人能帮我吗?

4

1 回答 1

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

它还使查询更易于理解。

于 2013-02-08T14:08:39.487 回答