从一系列交易中获取最新状态

时间:2018-07-20 14:38:30

标签: sql-server tsql sql-server-2016

我在黑暗中搜索。我什至不确定我的想法是否真的存在。

我有一个基于事务的数据库,其中包含一系列对记录的更新。每一行包含对一个或多个列的更新。有没有一种方法可以获取整个记录的最终状态。例如:

+-----------+---------+---------+--------+---------+
| update_id | country | status  | amount | device  |
+-----------+---------+---------+--------+---------+
|         1 | UK      | valid   |    100 | iPhone  |
|         2 |         | invalid |        |         |
|         3 |         |         |    200 | Android |
|         4 | DE      |         |    300 |         |
|         5 |         | valid   |        | Android |
|         6 |         |         |     50 |         |
|         7 | FR      |         |    350 |         |
|         8 |         |         |        | iPhone  |
+-----------+---------+---------+--------+---------+

这里的最终状态是:

FR | valid | 350 | iPhone

是否有一种方法可以通过一种查询或其他方法来获取该信息(但对于数百万个唯一记录和数百个列)?

目前,我唯一能想到的方法是使用游标并更新最终状态表,但这需要花费很多时间。

1 个答案:

答案 0 :(得分:1)

您可以使用子查询,但必须为每列编写一个子查询:

declare @tmp table (update_id int, 
     country varchar(2), 
     status varchar(10), 
     amount int, 
     device varchar(20))

insert into @tmp values
 (1 , 'UK'    , 'valid'   ,    100 , 'iPhone' )
,(2 , null    , 'invalid' ,   null ,  null    )
,(3 , null    , null      ,    200 , 'Android')
,(4 , 'DE'    , null      ,    300 , null     )
,(5 , null    , 'valid'   ,   null , 'Android')
,(6 , null    , null      ,     50 , null     )
,(7 , 'FR'    , null      ,    350 , null     )
,(8 , null    , null      ,   null , 'iPhone' )

select 
(select top 1  country from @tmp where country is not null order by update_id desc) as country,
(select top 1  status  from @tmp where status  is not null order by update_id desc) as status,
(select top 1  amount  from @tmp where amount  is not null order by update_id desc) as amount,
(select top 1  device  from @tmp where device  is not null order by update_id desc) as device

结果:

enter image description here

否则,您可以使用SQL Server元数据中的所有列生成动态TSQL语句。