SQL从具有聚合函数的另一个表插入表变量?

时间:2015-03-17 16:49:37

标签: sql sql-server sql-server-2008 tsql

我的源表是一个包含数千条记录的表。主键是[data_serial_num]列。

SELECT TOP 1000
    [data_serial_num]
   ,[foreign_serial_num]
   ,[msg_id]
   ,[data_value]
   ,[timestamp]
   ,[a]
   ,[b]
FROM [external_data]

我以为我会创建一个表变量来保存由[foreign_serial_num]和[msg_id]组成的唯一复合键,它还包含[data_value]和[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)
)

所以要插入表变量,我想我会做这样的事情:

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

该插入显然不起作用,因为[data_value]必须在group by子句中,但不会返回唯一记录。

的工作原理如下所示,但我不知道如何将[data_value]列和数据放入表变量中。

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 

示例预期输出:

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

所以我的问题是,将[external_data]表中的[data_value]放入我的表变量,同时保持复合主键[foreign_serial_num]和[msg_id]以及来自[timestamp的最新时间]的好方法是什么? ]

1 个答案:

答案 0 :(得分:1)

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