SQL Server:在聚合函数中使用用户定义的列

时间:2013-06-17 19:13:34

标签: sql sql-server tsql

例如,我有

SELECT SUBSTRING([Path], 0, 5) AS [Directory]
      , COUNT([Directory])
FROM [MyDatabase]
GROUP BY [Directory];

但是我得到了一个"无效的列名"错误。

2 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT SUBSTRING([Path], 0, 5) AS [Directory]
      , COUNT(1)
FROM [MyDatabase]
GROUP BY SUBSTRING([Path], 0, 5);

答案 1 :(得分:1)

问题是count()中使用的列名中的别名,我也看不出为什么只需要计数时需要两列。尝试

SELECT COUNT(SUBSTRING([Path], 0, 5))      
    FROM [MyDatabase];

如果您需要两列,请点击此处:

   SELECT SUBSTRING([Path], 0, 5) AS [Directory]
  , COUNT(SUBSTRING([Path], 0, 5) )
   FROM [MyDatabase]
   GROUP BY SUBSTRING([Path], 0, 5);