我有一个非常胖的表,列数超过100列。我想计算一列的值的数量。但为了做到这一点,我必须按所有其他列进行分组(这很痛苦)。有没有办法按除那个列之外的所有列对表进行分组?
它的工作原理如下:
select * [except col],count(col)
from table
group by * [except col];
表格如下:
(Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9.....,Col100)
(1,1,2,2,3,4,5,6......,X)
(1,1,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,X)
(1,0,2,2,3,4,5,6......,Y)
(1,0,2,2,3,4,5,6......,Z)
结果应该是
(1,1,2,2,3,4,5,6......,2)
(1,0,2,2,3,4,5,6......,4)
答案 0 :(得分:0)
同意戈登,如果你仍然想尝试传统方式而不想提及100列。
试试这个:
declare @Colsql Nvarchar(Max)
Select @ColSql = isnull(@ColSql + ',','') + '['+c.name+']'
from sys.tables t inner join sys.columns c
on t.object_id = c.object_id
inner join sys.schemas sc
on t.schema_id = sc.schema_id
Where t.name = @TableName and sc.name = @SchemaName
and c.name <> @ColumnToExclude
Exec('Select ' +@ColSql+ 'Count(@ColumnToExclude) From @TableName Group By '+@ColSql)