获取表SQL Server中每列的每个值的计数

时间:2014-01-23 16:14:50

标签: sql sql-server

所以我看了这个问题,这个问题非常相似,但缺少一个关键部分:SQL Server count number of distinct values in each column of a table

所以在那个问题中,他们希望每列都有不同的计数。我想要做的是获取表中每列的每个不同值的计数(我正在为特定数据库中的所有表执行此操作,这就是为什么我要尝试自动化这个尽可能)。目前我的代码看起来像我必须为每一列运行:

select mycol1, COUNT(*) as [Count] 
from mytable
group by mycol1
order by [Count] desc

理想情况下,我的输出看起来像这样:

ColumnName1 Count
val1        24457620
val2        17958530
val3        13350

ColumnName2 Count
val1        24457620
val2        17958530
val3        13350
val4 12

等表格中的所有列

下面的答案(由@beargle提供)来自上一个问题,真的接近我想要做的事情,但我似乎无法想办法让它发挥作用对于我想要做的事情,我将不胜感激任何帮助。

DECLARE @Table SYSNAME = 'TableName'; 

-- REVERSE and STUFF used to remove trailing UNION in string
SELECT REVERSE(STUFF(REVERSE((SELECT 'SELECT ''' + name 
                                     + ''' AS [Column], COUNT(DISTINCT(' 
                                     + QUOTENAME(name) + ')) AS [Count] FROM ' 
                                     + QUOTENAME(@Table) + ' UNION ' 
                              -- get column name from sys.columns  
                              FROM   sys.columns 
                              WHERE  object_id = Object_id(@Table)
                              -- concatenate result strings with FOR XML PATH
                              FOR XML PATH (''))), 1, 7, ';'));

3 个答案:

答案 0 :(得分:1)

您可以使用:

DECLARE @Table SYSNAME = 'TableName'; 
DECLARE @SQL NVARCHAR(MAX) = ''
SELECT @SQL = STUFF((SELECT ' UNION SELECT ''' + name 
                            + ''' AS [Column], ' 
                            + 'CAST(' + QUOTENAME(Name)
                            + ' AS NVARCHAR(MAX)) AS [ColumnValue], COUNT(*) AS [Count] FROM ' 
                            + QUOTENAME(@Table) + ' GROUP BY ' + QUOTENAME(Name)
                    FROM   sys.columns 
                    WHERE  object_id = Object_id(@Table)
                    -- concatenate result strings with FOR XML PATH
                    FOR XML PATH ('')), 1, 7, '');

EXECUTE sp_executesql @SQL;

哪个会生成SQL如下所示,对于包含两列(Column1和Column2)的表

SELECT 'Column1' AS [Column], 
        CAST([Column1] AS NVARCHAR(MAX)) AS [ColumnValue], 
        COUNT(*) AS [Count] 
FROM    [TableName] 
GROUP BY [Column1] 
UNION 
SELECT  'Column2' AS [Column], 
        CAST([Column2] AS NVARCHAR(MAX)) AS [ColumnValue], 
        COUNT(*) AS [Count] 
FROM    [TableName] 
GROUP BY [Column2]

修改

如果您想为每列添加新的结果集,请使用:

DECLARE @Table SYSNAME = 'TableName'; 
DECLARE @SQL NVARCHAR(MAX) = '';
SELECT @SQL = (SELECT ' SELECT ' + QUOTENAME(Name) 
                        + ', COUNT(*) AS [Count] FROM ' 
                        + QUOTENAME(@Table) + ' GROUP BY ' + QUOTENAME(Name) + ';'
                FROM   sys.columns 
                WHERE  object_id = Object_id(@Table)
                -- concatenate result strings with FOR XML PATH
                FOR XML PATH (''));

EXECUTE sp_executesql @SQL;

哪个会生成SQL Like:

SELECT  [Column1], 
        COUNT(*) AS [Count] 
FROM    [callsupplier] 
GROUP BY [Column1];

SELECT  [Column2], 
        COUNT(*) AS [Count] 
FROM    [callsupplier] 
GROUP BY [Column2];

答案 1 :(得分:0)

以为我会在等待备份恢复的时候捅这个

希望这能满足您的需求

create Table #Temp 
(tableName varchar(100),
columnName varchar(100),
value varchar(1000),
distinctItems int)

Declare @tabName as varchar(100)
Declare @colName as varchar(100)
Declare @tabid as int

Declare cursorTables Cursor
for 
select t.object_id , t.name , c.name from sys.tables t inner join sys.columns c on     t.object_id = c.object_id

open cursorTables 
Fetch Next from cursorTables into 
@tabid,@tabName,@colName


while @@Fetch_Status = 0 
Begin

declare @query as nVarchar(1000)
set @query  = 'Insert into #Temp SELECT    ''' + @tabName + '''  , '''+ @colName +''', '     + @colName + ',  COUNT([' + @colName +']) AS Expr1 FROM          [' + @tabName+ '] group by     [' + @colName + ']'
print @query
exec sp_executesql @query

Fetch Next from cursorTables into 
@tabid,@tabName,@colName


End 

Close cursorTables
Deallocate cursorTables

select * from #temp

drop table #temp

在PK值上产生一些不太有用的结果,我怀疑它不会对大于varchar(1000)的列有效,但对我的dbs的fe有效

答案 2 :(得分:0)

这个版本是一个很好的片段:

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += 'SELECT ''' + t.name + ''', ''' + c.name + ''', ' + c.name + ', COUNT(' + c.name + ') AS C FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ' GROUP BY ' + c.name + ';' + CHAR(13)
    FROM sys.tables AS t
    INNER join sys.columns c on t.object_id = c.object_id
    INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] 
    WHERE s.name LIKE 'stage' AND t.name LIKE 'table' AND c.name LIKE '%whatever%';

--PRINT @sql;
EXEC sp_executesql @sql