这是我试图解决的一个棘手的场景。Table A1:有4列。并且这个表每2天更新一次。
id name fav_color date
2051 joe white 07/21
2052 John green 07/212天后,记录被更新,table A1看起来像这样。
id name fav_color date
2051 joe blue 07/23
2052 Rick green 07/23Table A2:这是一个历史表,它捕获了对table A1所做的所有更改。
id updated_column update_dt old_value new_value
2051 fav_color 07/23 white blue
2052 Name 07/23 John Rick 现在,企业希望在月底看到表A1的每月快照。基本上我想要一个这样的每月快照。
id name fav_color date
2051 joe white 07/21
2051 joe blue 07/23
2052 John green 07/21
2052 Rick green 07/23请告诉我如何做到这一点。
发布于 2015-07-24 13:08:36
SELECT id,name,fav_color,date
FROM tableA1
UNION ALL
SELECT tableA2.id,
CASE WHEN tableA2.updatedColumn ='name'
THEN tableA2.oldValue
ELSE tableA1.name END,
CASE WHEN tableA2.updatedColumn ='fav_color'
THEN tableA2.oldValue
ELSE tableA1.fav_color END,
tableA2.update_dt
FROM tableA2
INNER JOIN tableA1 ON tableA2.id=tableA1.id
ORDER BY id发布于 2015-07-24 14:57:41
一种非常原始、缓慢而且可能不完整的方法,它或多或少应该返回您需要的内容:
SELECT
dates.id,
dates.date,
(SELECT TOP (1) name.new_value
FROM A2 name
WHERE name.id = dates.id and name.date <= dates.date and name.updated_column = 'name') as name,
(SELECT TOP (1) favcol.new_value
FROM A2 favcol
WHERE favcol.id = dates.id and favcol.date <= dates.date and favcol.updated_column = 'fav_color') as fav_color
FROM A2 dates按dates.id、dates.date排序
第一个值将被忽略。这可能是一个起点。
发布于 2015-07-24 21:08:54
有很多依赖项,但像这样的东西可能会做到这一点。
select
name.id
, name.name
, color.fav_color
, color.update_dt
from
(select
id
,update_dt
,new_value
from a2
where update_column = 'fav_color') color
join
(select
id
,update_dt
,new_value
from a2
where update_column = 'name') name
on color.id = name.id and color.update_dt = name.update_dt
order by color.update_dt, name.idhttps://stackoverflow.com/questions/31602270
复制相似问题