行列转换的一个解决思路,欢迎提意见
工作中常需要把数据库中某数据按照某列转成行。而展现的工具可能又只支持1句SQL完成,所以就考虑写视图解决。但是写此类SQL既繁琐,又容易出错,所以想写一个自动生成的脚本处理。
解决的问题,例:
表结构为:tab1
orgid(机构) gender(性别) ,itemid(项目) ,val(值)
0322 ,0,A,1
0322 ,0,B,4
0321 ,1,C,5
0324 ,1,C,3
展现效果:
0322,0,1,4,0
0321,0,0,0,5
0324,0,0,0,3
解决方法:
配置文件: SQL.txt
V_tab1.tab1.orgid,gender.VAL.itemid.A,B,C
awk -F'.' '{ test = $6 alen=split(test,cols,","); for( idx=1;idx<=alen;idx++) {sqlalias[idx]="v" idx "_" $4 } print " DROP VIEW " $1 " ; " print " CREATE VIEW " $1 " \n AS " print "SELECT " $3 "," for( idx=1;idx<=alen;idx++) { if( idx == alen ) print " \t sum(v" idx "_" $4 ") AS v" idx "_" $4 else print " \t sum(v" idx "_" $4 ") AS v" idx "_" $4 " ," } print "FROM (" for( idx=1;idx<=alen;idx++) { csql = "\tSELECT " $3 "," "\n \t \t " if( idx != 1 ) csql = "\tUNION \n" csql for( i=1;i<=alen;i++) { if( i == idx ) csql = csql $4 else csql = csql " 0 " csql = csql " AS " sqlalias[i] if( i != (alen) ) csql = csql " , " } csql = csql " \tFROM " $2 " WHERE " $5 "='\''" cols[idx] "'\''" print csql } print " ) aaa " print " GROUP BY " $3 ";" }' SQL.txt > test.sql
DROP VIEW v_tab1 ; CREATE VIEW v_tab1 AS SELECT orgid,gender, sum(v1_VAL) AS v1_VAL , sum(v2_VAL) AS v2_VAL , sum(v3_VAL) AS v3_VALFROM (SELECT orgid,gender, VAL AS v1_VAL , 0 AS v2_VAL , 0 AS v3_VAL FROM tab1 WHERE itemid='A'UNION SELECT orgid,gender, 0 AS v1_VAL , VAL AS v2_VAL , 0 AS v3_VAL FROM tab1 WHERE itemid='B'UNION SELECT orgid,gender, 0 AS v1_VAL , 0 AS v2_VAL , VAL AS v3_VAL FROM tab1 WHERE itemid='C' ) aaa GROUP BY orgid,gender;
select * from v_tab1