这是我最初的有效查询:
DECLARE @total AS FLOAT;
SET @total =(SELECT COUNT(*) FROM Crimes)
SELECT
Areas.Area,
Areas.AreaName,
COUNT(*) AS Total,
Round(CONVERT(float,(COUNT(*) / @total) * 100),3)
FROM Areas
INNER JOIN Crimes
ON(Areas.Area = Crimes.Area)
GROUP BY
Areas.AreaName,
Areas.Area
我所做的唯一更改是将聚合函数重命名为“ Percent”,这就是说Area和AreaName两列存在无法绑定的问题,我不确定为什么。
新更改:
DECLARE @total AS FLOAT;
SET @total =(SELECT COUNT(*) FROM Crimes)
SELECT
Areas.Area,
Areas.AreaName,
COUNT(*) AS Total,
Round(CONVERT(float,(COUNT(*) / @total) * 100),3) AS Percent
FROM Areas
INNER JOIN Crimes
ON(Areas.Area = Crimes.Area)
GROUP BY
Areas.AreaName,
Areas.Area
答案 0 :(得分:2)
PERCENT
是SQL Server中的关键字。尝试使用其他别名,例如Pct
:
SELECT
a.Area,
a.AreaName,
COUNT(*) AS Total,
Round(CONVERT(float, (COUNT(*) / @total) * 100), 3) AS Pct
FROM Areas a
INNER JOIN Crimes c
ON a.Area = c.Area
GROUP BY
a.AreaName,
a.Area;
请注意,我也向您的查询中引入了表别名,这使代码不太冗长,更易于阅读。
您也可以在方括号中使用[Percent]
。但是,这带来了这样的风险,即有人在子查询您的查询时也必须转义该别名。因此,我宁愿完全避免为列名和表名使用关键字。