1,unpivot 是将列转为行显示,很多时候,我们用多个列了显示同一个对象不同维度得数据,如果需要数据关联,肯定需要转为横向显示!
思路就是:有一列显示多列的名称,有一列显示列名对应的值
上案例:
要达到得目的是把 spee1,spee2,,,等列转为横向显示,看看得到得效果
效果很明显,给上sql语句
SELECT
[data], [time] ,
up.speeName,
up.speeVal
FROM
[YY2FSC].[dbo].[speetab_1_12]
unpivot(speeVal for speeName in (spee1, spee2,spee3, spee4 , spee5, spee6)) up
WHERE
CAST([data] as datetime) >='2023-05-10 0:00:00' and CAST([data] as datetime) <= '2023-05-10 0:59:59'
unpivot(speeVal for speeName in (列名1, 列名2,列名3, 列名4 , 列名5, 列名6)) up
unpivot紧跟表名,up 是别名,不可缺少, speeName 显示转换的列名,speeVal 代表了那么多列的值,然后显示出来就可以了,比较简单!!
2,pivot 是将行转为列显示, 下面这个案例,是把整点的数据按照小时显示成列,纵向排列
列转行之后的效果图为:
效果很明显,给上sql语句
select
createtime,
[0] as [data0],[1] as [data1],[2] as [data2],[3] as [data3],[4] as [data4],[5] as [data5],
[6] as [data6],[7] as [data7],[8] as [data8],[9] as [data9],[10] as [data10],
[11] as [data11],[12] as [data12],[13] as [data13],[14] as [data14],[15] as [data15],
[16] as [data16],[17] as [data17],[18] as [data18],[19] as [data19],[20] as [data20],
[21] as [data21],[22] as [data22],[23] as [data23]
from [YY2FSC_DW].[dbo].[TB_DY_ByHour_Report]
pivot(min([VirtualVoltage] ) for [hour] in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23]))as pvt
order by createtime
pivot(min([VirtualVoltage] ) for [hour] in ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23]))as pvt
in里面的就是hour这列所有的值,将这个值变成了列,一天24小时,从0-23,注意in里面的值必须带有中括号 eq:[0]或者['0'],根据要转的列的类型确定。min是有最小值,但是自己做好分组就可以了! pvt 是别名,不可缺少
其实原理思考清楚了,把多列合并成为一行,把多行显示为列就明白了