• 【TransactSQL】计算整个表中所有值的出现的次数


    一个表有3列,5行,那么一共有15个值,现在要计算整个表中所有值在表中出现的次数,不过这里表的列数是不确定的,上面的例子是3列,实际上也有可能是5列、20列,所以解决问题的步骤是这样的:

    1、必须知道有多少列,然后构造动态语句,把这些列合并到一列中。

    2、然后去重计算出所有的可能值。

    3、最后计算每个值在表中出现了多少次。

    if(OBJECT_ID('dbo.wc') is not null)
    	drop table dbo.wc
    go
    
    
    create table wc
    	(
    	a nvarchar(100),
    	b nvarchar(100),
    	c nvarchar(100)
    	)
    	
    insert into wc
    values('1','2','3'),
          ('a','f','d'),
          ('2','b','c'),
          (null,'c','w'),
          ('3','d',null)
    
    
    declare @temp table (cn nvarchar(100));
    
    declare @i int = 1;
    
    declare @v varchar(max)='';
    
    declare @column varchar(100)='';
    
    while @i <= (
    				select count(*)
    				from sys.tables t
    				inner join sys.columns c
    						on t.object_id =c.object_id 
    				where t.name = 'wc'   
                 )
    begin
        select @column = c.name
    	from sys.tables t
    	inner join sys.columns c
    			on t.object_id =c.object_id 
    	where t.name = 'wc'
    	      and c.column_id = @i 
    	      
    	set @i = @i + 1 
        
        set @v = @v + ' select '+ @column + ' from wc union all'
    
    end
    
    select @v = LEFT(@v,len(@v)-LEN('union all'))
    --select @v
    
    insert into @temp
    exec (@v)
    
    ;with a
    as
    (
    select cn
    from @temp
    where cn is not null
    group by cn
    )      
    
    select a.cn,
           COUNT(t.cn)
    from a
    inner join @temp t
            on a.cn = t.cn
    group by a.cn
     


     

  • 相关阅读:
    mysql-proxy使用中的问题
    iOS中利用CoreTelephony获取用户当前网络状态(判断2G,3G,4G)
    Django连接MySQL出错
    前后端分离
    django 安装指定版本
    问题
    算法面试
    记录docker for windows 时候的错误
    Django项目部署
    git 上传至github
  • 原文地址:https://www.cnblogs.com/momogua/p/8304609.html
Copyright © 2020-2023  润新知