对于数据可视化操作,很多时候chart需要的格式跟数据库一般查询查出的格式 不一样,导致需要对 sql查询出来的数进行行转列的操作,
什么是行专列, 就是如下
查询5小时内 每个小时两个智能电表有功电能数据对比 因为采集的数据是10分钟采集一次所以每个小时内数据起码有12条了, 用datepart 函数进行分割小时获得hour 列, 用max()函数获得小时内最大的时间值 成一个列 还有最大的realdata值,因为值是增长的,所以在此取最大值算是最新数据 通过group by 分组
select deviceName, datepart(hour,updateTime) hour,max(updateTime)datetime ,max(case attributeName when N'有功电能' then realData else 0 end) as Energy from AutoNetwork_MeterRealData where updateTime>DATEADD(HOUR,-5,GETDATE()) group by datepart(hour,updateTime),deviceName
最终得到数据
直接在sql 中把想要的格式 做出来, 我的做法是把 hour列的所有行转成列头 这样获取完数据后方便加工
select a.deviceName,max(case a.hour when 1 then a.Energy end)as '1',max(case a.hour when 2 then a.Energy end) as '2' , max(case a.hour when 3 then a.Energy end) as '3' ,max(case a.hour when 4 then a.Energy end) as '4' , max(case a.hour when 5 then a.Energy end) as '5' ,max(case a.hour when 6 then a.Energy end) as '6' , max(case a.hour when 7 then a.Energy end) as '7' ,max(case a.hour when 8 then a.Energy end) as '8' , max(case a.hour when 9 then a.Energy end) as '9' ,max(case a.hour when 10 then a.Energy end) as '10', max(case a.hour when 11 then a.Energy end) as '11',max(case a.hour when 12 then a.Energy end) as '12', max(case a.hour when 13 then a.Energy end) as '13',max(case a.hour when 14 then a.Energy end) as '14', max(case a.hour when 15 then a.Energy end) as '15',max(case a.hour when 16 then a.Energy end) as '16', max(case a.hour when 17 then a.Energy end) as '17',max(case a.hour when 18 then a.Energy end) as '18', max(case a.hour when 19 then a.Energy end) as '19',max(case a.hour when 20 then a.Energy end) as '20', max(case a.hour when 21 then a.Energy end) as '21',max(case a.hour when 22 then a.Energy end) as '22', max(case a.hour when 23 then a.Energy end) as '23',max(case a.hour when 0 then a.Energy end) as '0'from ( select deviceName, datepart(hour,updateTime) hour,max(updateTime)datetime ,max(case attributeName when N'有功电能' then realData else 0 end) as Energy from AutoNetwork_MeterRealData where updateTime>DATEADD(HOUR,-5,GETDATE()) group by datepart(hour,updateTime),deviceName)as a group by a.deviceName
用max 函数 hour列 的值 输出同行的另一列realdata的值,形成一个新列 ,借用max 生成新列