zoukankan      html  css  js  c++  java
  • 列数不定的行列变换续

    客户补充需求说只需要能打印出来前一篇(http://www.cnblogs.com/galaxyyao/archive/2009/02/17/1392119.html)中的需求,并不一定要完全创建符合需求的表,那样就简单多了,把相同siteno,subno,mv的值都并到同一行中就可以了。这次同样暂时没考虑性能,怎么方便怎么写。补充点图和代码:

    创建表结构:

    USE [TestDB1]
    GO

    /****** Object:  Table [dbo].[testtable2]    Script Date: 02/19/2009 13:46:24 ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[testtable4](
        
    [SiteNo] [varchar](10NULL,
        
    [SubNo] [varchar](10NULL,
        
    [MV] [varchar](10NULL,
        
    [Date] [varchar](20NULL
    ON [PRIMARY]

    GO

    插入值:

    先预处理值,再动态生成代码:

    SELECT 
    identity(int,1,1as id
    ,
    [SiteNo]
    ,
    [SubNo]
    ,
    [MV]
    ,
    [Date]
    into #temp1
    FROM [TestDB1].[dbo].[testtable4]

    --select * from #temp1

    CREATE TABLE #temp2(
        
    [SiteNo] [varchar](10NULL,
        
    [SubNo] [varchar](10NULL,
        
    [MV] [varchar](10NULL,
        
    [Date] [varchar](maxNULL
    ON [PRIMARY]

    declare @i int
    declare @siteno nchar(10)
    declare @subno nchar(10)
    declare @mv nchar(10)
    declare @date varchar(max)

    set @i=1
    while ((select COUNT(*from #temp1 where id=@i)>0)
    begin
        
    select @siteno = [siteno],@subno=subno,@mv=mv,@date=[DATE] from #temp1 where id=@i
        
    if ((select COUNT(*from #temp2 where [siteno]=@siteno and [subno]=@subno and [mv]=@mv)=0)
        
    begin
            
    insert into #temp2 values(@siteno,@subno,@mv,@date)
        
    end
        
    else
        
    begin
            
    update #temp2 set [date]=([date]+','+@datewhere [siteno]=@siteno and [subno]=@subno and [mv]=@mv
        
    end
        
    set @i=@i+1
    end

    --select * from #temp2

    declare @sql varchar(4000)
    set @sql = 'select [SiteNo],[SubNo]'
    select @sql = @sql + ',max(case [MV] when '''+[MV]+''' then [Date] end) as ['+[MV]+']'
    from (select distinct [MV] from [testtable2]as a
    select @sql = @sql+' from #temp2 group by [SiteNo],[SubNo] order by [SiteNo]'
    exec(@sql)

    drop table #temp1
    drop table #temp2

    最终结果

  • 相关阅读:
    统计知识选讲(二)——主成分分析(PCA)的推导和应用
    统计知识选讲(一)——主成分分析(PCA)的思想
    数模学习笔记(八)——遗传算法
    数模学习笔记(六)——灰色系统
    数模学习笔记(五)——BP神经网络
    数模学习笔记(四)——AHP
    数模学习笔记(三)
    数模学习笔记(二)
    推荐决策 对比user-based 和item-based推荐算法
    Mysql事件学习
  • 原文地址:https://www.cnblogs.com/galaxyyao/p/1394180.html
Copyright © 2011-2022 走看看