2

我正在使用 SQL Server 2008 R2,但我的动态 T-SQL 查询遇到了问题。我相信这与我的语法有关,但是当从动态 T-SQL 上下文中取出时,它可以在新的查询窗口中运行。当作为存储过程运行时,有时会出现以下错误:

选择列表中的列dbo.Birds.weight无效,因为它既不包含在聚合函数中,也不包含在GROUP BY 子句中。

T-SQL 代码:

set @sql =
N'select FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval as ''Weight'',
COUNT(1) as ''Count''
FROM dbo.Birds
WHERE
weight >= @INPUTminwgt AND 
weight <= @INPUTmaxwgt
GROUP BY FLOOR(weight*@INPUTconversion) 
order by weight asc'


set @params =
N'@INPUTminwgt float, 
@INPUTmaxwgt float, 
@INPUTconversion float,
@INPUTinterval float';

exec sp_executesql @sql, @params,  
@INPUTminwgt = @BirdMinWeight, 
@INPUTmaxwgt = @BirdMaxWeight,
@INPUTconversion = @conversion,
@INPUTinterval = @interval;

权重到小数点后 1000 位(例如 3.154)

@INPUTconversion = 1/interval

查询应返回按间隔分组的最小和最大重量参数之间的权重(例如,0.1 间隔将类似于 1.1、1.2、1.3、1.4,其中包含该重量跨度内的总鸡数)

任何帮助表示赞赏

4

2 回答 2

2

In the group by, *@INPUTintervals is missing.

It should be GROUP BY FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval

Also,you can't use the alias weight in your where and order by, you have to use FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval or dbo.Birds.weight cause here it's ambiguous which one you need.

set @sql =
N'select FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval as ''Weight'',
COUNT(1) as ''Count''
FROM dbo.Birds
WHERE
dbo.Birds.weight >= @INPUTminwgt AND 
dbo.Birds.weight <= @INPUTmaxwgt
GROUP BY FLOOR(weight*@INPUTconversion) *@INPUTinterval
order by FLOOR(weight*@INPUTconversion) *@INPUTinterval asc'
于 2012-10-01T17:02:39.987 回答
0

我的猜测是,它并没有完全认识到 dbo.Birds.Weight 与查询底部的“重量”相同。这当然很有趣,我不太清楚为什么会这样,但这可能会奏效:

set @sql = N'
SELECT 
  FLOOR(b.weight * @INPUTconversion) * @INPUTinterval as [Weight],
  COUNT(*) as ''Count''
FROM  dbo.Birds b
WHERE b.weight >= @INPUTminwgt 
AND   b.weight <= @INPUTmaxwgt
GROUP BY FLOOR(b.weight * @INPUTconversion) * @INPUTinterval
ORDER BY FLOOR(b.weight * @INPUTconversion) * @INPUTinterval'
于 2012-10-01T17:07:34.940 回答