简体   繁体   English

按SQL Server中的多列分组

[英]Group By Many Columns in SQL Server

I have a table whereby some rows are identical except for a single column. 我有一个表,除了一列之外,有些行是相同的。 I want to group by the identical rows and take the mean of the single column. 我想按相同的行分组并取单列的平均值。

For example I have the table: 例如,我有表:

A   B   C   D
-------------
a   b   c   2
a   b   c   2
a   b   c   5
d   e   f   8
d   e   f   10

Desired result: 期望的结果:

A   B   C   D
-------------
a   b   c   3
d   e   f   9

I could easily do this by: 我可以通过以下方式轻松完成:

SELECT A, B, C, AVG(D)
FROM [table] 
GROUP BY A, B, C

My issue is I have many columns and it is cumbersome to manually type every column to GROUP BY. 我的问题是我有很多列,手动键入每个列到GROUP BY是很麻烦的。 For example, I want to do this but its not possible: 例如,我想这样做,但它不可能:

SELECT (* but not D), AVG(D)
FROM [table] 
GROUP BY (* but not D)

The two issues are that I don't know how to form a wildcard that excludes D, and also it seems GROUP BY does not work with wildcards. 这两个问题是我不知道如何形成一个排除D的通配符,而且似乎GROUP BY不能用于通配符。

What is the elegant way to do this? 这样做的优雅方式是什么?

Btw, the original table resulted by a left join that matched on non-unique values. 顺便说一句,原始表由左连接产生,匹配非唯一值。

Unfortunately there isn't a magic way to do it, however it can made much easier with SSMS: 不幸的是,没有一种神奇的方法可以做到这一点,但是使用SSMS可以更轻松:

  • Right click the table 右键单击表格
  • Script table as -> 脚本表为 - >
  • Select to -> 选择 - >
  • New query window 新的查询窗口

This gives you have a formatted SELECT list that you can remove the aggregate columns from and copy-paste to your GROUP BY . 这使您有一个格式化的SELECT列表,您可以从中删除聚合列并将其复制粘贴到GROUP BY It's at least a bit better than starting from scratch. 它至少比从头开始要好一点。

You can use dynamic SQL for this. 您可以使用动态SQL。
See working demo 看工作演示

DECLARE @sqlCommand nvarchar(max)
DECLARE @columnList nvarchar(max)

SET @columnList= STUFF((SELECT ',' + c.name
    from sys.columns c join sys.tables t on c.object_id =t.object_id
    and t.name ='yourtable' and c.name <>'D'
FOR XML PATH(''), Type
).value('.', 'NVARCHAR(MAX)') 
,1,1,'')
SET @sqlCommand = 'SELECT ' + @columnList + ', AVG(D) as D FROM [yourtable] GROUP BY  ' + @columnList
EXEC (@sqlCommand)

You can also use Select name from sys.columns where table_name = <table> 您还可以使用Select name from sys.columns where table_name = <table>

to get all the columns of the table and specify it in your Group By section 获取表的所有列并在“分组依据”部分中指定它

In SSMS , expand the Object Explorer to the desired table. SSMS ,将Object Explorer展开到所需的表。 Expand the table, you will see folder Column . 展开表格,您将看到文件夹Column Just drag the folder to the query window and it will list the columns of the table. 只需将文件夹拖到查询窗口,它就会列出表格的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM