106.行列互换复杂交叉表

旧城等待, 2024-02-19 18:59 108阅读 0赞
  1. --创建测试数据
  2. create table 表(年 int,项目 varchar(10)
  3. ,平均值 decimal(20,1)
  4. ,最大值 decimal(20,1)
  5. ,最小值 decimal(20,1)
  6. ,超标率 decimal(20,1)
  7. )
  8. insert into
  9. select 2001,'项目1',1.5,2.1,1.1,0.1
  10. union all select 2001,'项目2',2.0,5.0,1.5,5.5
  11. union all select 2003,'项目10',2.1,5.2,2.5,5.5
  12. go
  13. --处理
  14. declare @s varchar(8000),@s1 varchar(8000),@s2 varchar(8000),@s3 varchar(8000)
  15. --处理项目
  16. set @s=''
  17. select @s=@s+',['+项目+']=max(case 项目 when '''''+项目+''''' then 值 end)'
  18. from(select distinct 项目,id=cast(right(项目,len(项目)-2) as int) from
  19. ) a order by id
  20. --处理字段(指标)
  21. select @s1='',@s2='',@s3=''
  22. select @s1=@s1+',@'+id+' varchar(8000)'
  23. ,@s2=@s2+'
  24. set @'+id+'=''select 年,项目,id='+id+
  25. ',内容='''''+name+''''',值='+name+' from 表'''
  26. ,@s3=@s3+'+'' union all ''+@'+id
  27. from(
  28. select name,id=cast(colid as varchar),colid
  29. from syscolumns where object_id('表')=id
  30. and name not in('年','项目')
  31. ) a order by colid
  32. select @s1=substring(@s1,2,8000),@s3=substring(@s3,16,8000)
  33. exec('declare '+@s1+'
  34. '+@s2+'
  35. exec(''select 年,内容'+@s+' from(''+'
  36. +@s3+'+'') a group by 年,id,内容 order by 年,id'')')
  37. go
  38. --删除测试数据
  39. drop table
  40. /*--测试结果
  41. 年 内容 项目1 项目2 项目10
  42. ----------- ------ ---------------------- ---------------------- ----------------------
  43. 2001 平均值 1.5 2.0 NULL
  44. 2001 最大值 2.1 5.0 NULL
  45. 2001 最小值 1.1 1.5 NULL
  46. 2001 超标率 .1 5.5 NULL
  47. 2003 平均值 NULL NULL 2.1
  48. 2003 最大值 NULL NULL 5.2
  49. 2003 最小值 NULL NULL 2.5
  50. 2003 超标率 NULL NULL 5.5
  51. (所影响的行数为 8 行)
  52. --*/

发表评论

表情:
评论列表 (有 0 条评论,108人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL面试题(行列互换

    有一个SQL面试题(行列互换)在面试中出现的概率极高,最近有学生出去面试仍然会遇到这样的题目,在这里跟大家分享一下。 题目:数据库中有一张如下所示的表,表名为sales。