SQL查询,用于选择每天的最后一行

时间:2017-05-16 17:30:28

标签: mysql sql

我需要你的帮助。我有一张桌子(senosrId,时间,数据),我需要为最近10天的其中一个传感器选择每天的最新数据。

1 个答案:

答案 0 :(得分:-1)

对于MS SQL,经过测试,编译:

测试表:

CREATE TABLE [dbo].[DataTable](
    [SensorId] [int] NULL,
    [SensorTime] [datetime] NULL,
    [SensorData] [int] NULL
)

多次运行以插入演示数据:

insert into DataTable (SensorId, SensorTime, SensorData) select 1, getdate() - 15*rand(), convert(int, rand()*100)

获取过去10天中的每一天的最后一个值(实际答案):

select top 10 * 
    from DataTable 
    inner join (    -- max time for each day
         select SensorId, max(SensorTime) as maxtime, convert(varchar(10), SensorTime, 112) as notneededcolumn 
            from DataTable
            group by SensorId, convert(varchar(10), SensorTime, 112)
    ) lastvalues on lastvalues.maxtime=DataTable.SensorTime and lastvalues.SensorId=DataTable.SensorId
    where DataTable.SensorId=1
    order by DataTable.SensorTime desc

示例输出:

1   2017-05-17 21:07:14.840 54  1   2017-05-17 21:07:14.840 20170517 
1   2017-05-16 23:35:37.220 94  1   2017-05-16 23:35:37.220 20170516
1   2017-05-14 22:35:48.970 8   1   2017-05-14 22:35:48.970 20170514
1   2017-05-13 14:56:34.557 94  1   2017-05-13 14:56:34.557 20170513
1   2017-05-12 22:28:55.400 89  1   2017-05-12 22:28:55.400 20170512