首页 > 解决方案 > 我需要对结果集进行分组

问题描述

我正在使用 SQL Server2014。我有个问题

select *
     from (
        select [DataTime] datatime,[Temperature] temperature,[Humidity] humidity, 
        b.[serialnumber] serialnumber, Row_Number() OVER(ORDER BY a.datatime) rownum 
        from [dbo].[datalog] a,[report_devicelist] b where a.deviceno = b.deviceno and b.report_no='201906140013yEcD'
        and a.datatime between '2019-04-09 15:05:00' and '2019-04-09 16:20:52'
    ) as t where rownum between 1 and 50
time    temperature humidity    serialnumber    rownum
2019-04-09 15:05:01 268 0   ch4 1
2019-04-09 15:05:01 272 0   ch5 2
2019-04-09 15:05:01 266 0   ch6 3
2019-04-09 15:05:01 264 0   ch7 4
2019-04-09 15:05:01 263 0   ch8 5
2019-04-09 15:06:01 253 0   ch3 15
2019-04-09 15:06:01 245 0   ch2 16
2019-04-09 15:06:01 257 0   ch1 17
2019-04-09 15:06:01 272 0   ch14    18
2019-04-09 15:06:01 250 0   ch13    19
2019-04-09 15:06:01 254 0   ch12    20
2019-04-09 15:06:01 263 0   ch11    21
2019-04-09 15:06:01 256 0   ch10    22



time    ch1 ch2 ch3 ch4 ch5 ch6 ch7 ch8 ch9
2019/03/05 11:41:01 16.9    15.3    17.2    17.1    15.2    16.9    17.4    16.1    17.1 
2019/03/05 11:42:01 16.5    15.4    16.8    16.6    14.8    16.7    17.0    15.9    16.3 
2019/03/05 11:43:01 16.3    15.5    16.6    16.2    14.5    16.5    16.6    15.9    15.9 
2019/03/05 11:44:01 16.4    15.3    16.7    15.9    14.4    16.9    16.3    16.1    15.6 
2019/03/05 11:45:01 16.8    15.2    16.7    15.7    14.3    16.7    16.0    16.6    15.4 
2019/03/05 11:46:01 16.6    15.1    16.9    15.4    14.2    16.5    15.8    16.7    15.3 
2019/03/05 11:47:01 16.6    15.2    17.4    15.4    14.3    17.7    15.9    16.6    15.3 
2019/03/05 11:48:01 16.2    15.0    17.1    15.4    14.2    17.5    15.8    16.4    15.3 
2019/03/05 11:49:01 15.8    14.5    16.8    15.2    14.1    17.1    15.5    16.1    15.1 
2019/03/05 11:50:01 15.2    13.7    16.4    14.8    13.9    16.4    14.9    15.5    14.8 
2019/03/05 11:51:01 14.6    12.7    15.8    14.3    13.5    15.6    14.2    14.8    14.2

我需要根据事件对以下结果进行分组。也就是每个时间点需要列出所有的序号温度。我尝试使用datatime group by。但是其他列不在聚合函数中。

标签: sqlsql-server

解决方案


似乎您需要将pivot表格用作:

select top 50 datatime,[ch1], [ch2], [ch3], [ch4], [ch5], [ch6], [ch7], [ch8], [ch9]
from
    (select 
           [DataTime] datatime,[Temperature] temperature 
            b.[serialnumber] serialnumber
    from [dbo].[datalog] a,[report_devicelist] b where a.deviceno = b.deviceno and b.report_no='201906140013yEcD'
         and a.datatime between '2019-04-09 15:05:00' and '2019-04-09 16:20:52'
    ) AS SourceTable
    PIVOT  
    (  
    AVG(temperature) 
    FOR serialnumber IN ([ch1], [ch2], [ch3], [ch4], [ch5], [ch6], [ch7], [ch8], [ch9])  
    ) AS PivotTable
Order by datatime;

并将查询数量限制为top 50[datatime].


推荐阅读