Select查询动态列QUOTENAME MAX聚合函数

huangapple go评论57阅读模式
英文:

Select query dynamic column QUOTENAME MAX aggregate function

问题

DECLARE @var1 NVARCHAR(20)
DECLARE @sql NVARCHAR(255)

SET @var1 = '2018' -- this is the dynamic column, it will produce 2018, 2019, 2020 and so on
SET @sql = 'select MAX(ID) AS ColID, MAX(Name) AS ColName, ' + QUOTENAME(@var1, 'MAX()') + ' from [Table] GROUP BY ColID'

EXEC sp_executesql @stmt = @sql

但是,我遇到了一个错误:

列 'Table.2018' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。

英文:

I have dynamic query to show output DISTINCT using MAX() aggregate function fields.

DECLARE @var1 NVARCHAR(20)
DECLARE @sql NVARCHAR(255)

SET @var1 = '2018' -- this is the dynamic column, it will produce 2018, 2019, 2020 and so on
SET @sql = 'select MAX(ID) AS ColID, MAX(Name) AS ColName, ' + QUOTENAME(@var1, 'MAX()') + ' from [Table] GROUP BY ColID'

EXEC sp_executesql @stmt = @sql

but, I get an error:

> Column 'Table.2018' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

答案1

得分: 1

将变量列放入最大函数中:

SET @sql = '
select
  MAX(ID) AS ColID,
  MAX(Name) AS ColName,
  MAX(' + QUOTENAME(@var1) + ')
from [Table]
GROUP BY ColID
'
英文:

Place the variable column into the max function:

SET @sql = '
select
  MAX(ID) AS ColID,
  MAX(Name) AS ColName,
  MAX(' + QUOTENAME(@var1) + ')
from [Table]
GROUP BY ColID
'

huangapple
  • 本文由 发表于 2023年5月22日 09:40:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定