加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 如何在SQL Server查询中使用group by?

发布时间:2020-12-12 16:24:57 所属栏目:MsSql教程 来源:网络整理
导读:我在SQL Server中遇到组问题 我有这个简单的SQL语句: select * from Factors group by moshtari_ID 我收到此错误: Msg 8120,Level 16,State 1,Line 1 Column ‘Factors.ID’ is invalid in the select list because it is not contained in either an aggre
我在SQL Server中遇到组问题

我有这个简单的SQL语句:

select * 
from Factors 
group by moshtari_ID

我收到此错误:

Msg 8120,Level 16,State 1,Line 1
Column ‘Factors.ID’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

这是我没有分组的结果:

这是group by命令的错误:

我的问题在哪里?

解决方法

通常,一旦开始GROUPing,SELECT中列出的每个列都必须是GROUP中的列或其某些聚合.假设您有一个这样的表格:
| ID | Name        | City        |
|  1 | Foo bar     | San Jose    |
|  2 | Bar foo     | San Jose    |
|  3 | Baz Foo     | Santa Clara |

如果您想获得数据库中所有城市的列表,并尝试:

SELECT * FROM table GROUP BY City

…那会失败,因为你要求不在GROUP BY子句中的列(ID和Name).你可以改为:

SELECT City,count(City) as Cnt FROM table GROUP BY City

……那会得到你:

| City        | Cnt |
| San Jose    |  2  |
| Santa Clara |  1  |

…但不会得到你的身份证或姓名.你可以做更复杂的事情,例如subselects或self-joins,但基本上你正在尝试做的事情是不可能的.进一步细分你的问题(你希望数据看起来像什么?),然后从那里开始.

祝你好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读