sql - T-SQL - 必须在分组依据或聚合函数中有术语才能选择

标签 sql sql-server database sql-server-2008 tsql

给定以下选择语句:

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/

相关文章:

mysql cross join 进不去?

sql - 声明变量并在查询中使用

sql-server - 拆分表以每秒处理 100 次插入?

sql-server - CTRL + K、CTRL + F(格式代码)在 MS SQL Server 中不起作用

sql - 使用 Subselect 优化查询

java - csv 文件中的反斜杠

sql - 如何让员工的职能处于首位?

SQL 查询 : self join on subquery necessitates creating a separate (non-temporary) table?

database - 无法手动将数据保存在Grails中的数据库中,但是使用dbconsole可以很好地工作

sql - SQL中如何思考?