Reputation: 1107
My source table is a table with many thousands of records. Primary key is column [data_serial_num].
SELECT TOP 1000
[data_serial_num]
,[foreign_serial_num]
,[msg_id]
,[data_value]
,[timestamp]
,[a]
,[b]
FROM [external_data]
I thought I would create a table variable to hold a unique compound key made up of [foreign_serial_num] combined with [msg_id] that also contains the [data_value] and the most recent time from [timestamp].
declare @filtered_data table
(
foreign_serial_num bigint not null
,msg_id bigint not null
,data_value bigint
,timestamp datetimeoffset(7)
PRIMARY KEY(vehicle_serial_num, msg_id)
)
So to insert into the table variable I thought I would do something like this:
insert into @filtered_data
select foreign_serial_num, msg_id, data_value, max(timestamp) 'timestamp'
from external_data
group by foreign_serial_num, msg_id
That insert obviously doesn't work because [data_value] must be in the group by clause but that doesn't return unique records.
What does work is this below but I don't know how to get the [data_value] column and data into the table variable.
declare filtered_data table
(
foreign_serial_num bigint not null
,msg_id bigint not null
,timestamp datetimeoffset(7)
PRIMARY KEY(vehicle_serial_num, msg_id)
)
insert into filtered_data
select foreign_serial_num, msg_id, max(timestamp) 'timestamp'
from external_data
group by foreign_serial_num, msg_id
select * from filtered_data
Sample Expected output:
foreign_serial_num | msg_id | data_value | timestamp
20 | 1 | 0 | 2015-01-14 16:02:47.0000000 -08:00
20 | 2 | 45 | 2015-01-14 16:02:47.0000000 -08:00
20 | 3 | 10 | 2014-11-10 15:41:36.0000000 -08:00
155 | 1 | 0 | 2015-02-27 10:43:09.0000000 -08:00
155 | 2 | 33 | 2015-02-27 10:43:09.0000000 -08:00
155 | 3 | 0 | 2015-02-27 10:43:09.0000000 -08:00
So my question is, what is a good way to get the [data_value] from the [external_data] table into my table variable while keeping the compound primary key [foreign_serial_num] and [msg_id] along with the latest time from [timestamp]?
Upvotes: 0
Views: 823
Reputation: 45096
select * from
(
select foreign_serial_num, msg_id, data_value, timestamp
, row_number() over (partition by oreign_serial_num, msg_id order by timestamp desc) as rn
from external_data
) ordered
where ordered.rn = 1
Upvotes: 1