给定以下选择语句:
Select t.name, SUM(st.row_count) as row_count
From sys.dm_db_partition_stats st
join sys.tables t on t.object_id = st.object_id
join ClientUpdateConfig c on t.name = c.TableName
Where (index_id < 2) and schema_id = schema_id('dbo')
and t.type ='U'
group by t.name
我还想选择 c.RowID 作为附加字段。查询按原样工作,但如果我将 1 更改为:
Select t.name, SUM(st.row_count) as row_count, c.RowID as current_row
我得到错误:
Msg 8120, Level 16, State 1, Line 1 Column 'ClientUpdateConfig.RowID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
有人可以解释为什么我需要聚合函数(我假设是 SUM)或分组依据中的选择值来选择它吗?我不明白这个限制 - 如果我能理解为什么会这样,也许我可以调整我的查询设计。
最佳答案
因为它不知道选择哪个RowId。
你需要:
. . .
group by t.name, RowId
或:
select . . ., min(RowId) -- or max(RowId)
即使您知道每个名称只有一个 RowId,数据库也不知道这一点,因此您必须在查询中明确说明您要执行的操作。
关于sql - T-SQL - 必须在分组依据或聚合函数中有术语才能选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744899/