我正在尝试创建一个基本上重新显示日志表以提高可读性的报告,因此所有更改都捕获在两列中,一列原始值和一列当前值列,其中一个属性列标记了更改的内容。
为了便于测试,我为 SQL Server 创建了一个临时表。
declare @T table (Utility_ID int,
Utility_Record_ID int,
Organization_Name nvarchar(255),
Facility_Name nvarchar(255),
Space_Name nvarchar(255),
Utility_Name nvarchar(255),
MeterNumber nvarchar(255),
Data_Type nvarchar(255),
Reading decimal(18,2),
Consumption decimal(18,2),
Begin_Date datetime,
End_Date datetime,
[Estimated/Actual] nvarchar(255),
[Date-Time Of Change] datetime,
[changed By] nvarchar(100),
[Change Type] nVarchar(100)
)
insert into @T
select 11819, 38503, 'The Men Who Stare At Goats', 'BuildingA', NULL, 'Electricty for BuildingA', '9615(small meter)', 'Reading', 2369, 9.00, '2011 -06-30 00:00:00:000', NULL, 'Actual', '2012-03-07 09:26:53.590', 'Billy.Bob', 'Insert'
union all
select 11819, 38503, 'The Men Who Stare At Goats', 'BuildingA', NULL, 'Electricty For BuildingA', '9615(small meter)', 'Reading', 2372, 12.00, '2011 -06-30 00:00:00:000', NULL, 'Actual', '2012-05-01 10:30:40:237', 'Billy.Jean', 'Update'
union all
select 2000, 12345, 'Hotel', 'Fun House', 'My Gaff', 'Water For My Gaff', '987654321', 'Consumption', NULL, 500.00, '2011 -06-30 00:00:00:000', '2011 -08-30 00:00:00:000', 'Actual', '2013-05-01 10:30:40:237', 'Billy.NoMates', 'Insert'
我的障碍是我正在跟踪 c.Reading、c.Consumption、估计/实际、开始日期和结束日期的变化。如果其他字段值被更改,或者被另一个字段更改,我如何实现其他字段值以拉入 CurrentValue 和 PreviousValue 列?
我在下面尝试跟踪一列 [c.Consumption] 我已按 ID 分区并按记录的更改日期时间排序。
-- Get CurrentValue and PreviousValue with a Changed column
;with cte as
(
select *,
row_number() over(partition by Utility_Record_ID order by [Date-Time Of Change]) as rn
from @T
)
select
C.Utility_ID ,
C.Utility_Record_ID,
C.Organization_Name,
C.Facility_Name,
C.Space_Name,
C.Utility_Name,
C.MeterNumber,
C.Data_Type,
C.Reading,
C.Consumption,
C.Begin_Date,
C.End_Date,
C.[Estimated/Actual],
C.[Date-Time Of Change],
C.[changed By],
C.[Change Type],
C.Consumption as CurrentValue,
P.Consumption as PreviousValue,
case C.Consumption when P.Consumption then 0 else 1 end as Changed
from cte as C
LEFT OUTER JOIN cte as P
on C.Utility_Record_ID = P.Utility_Record_ID and
C.rn = P.rn + 1
这个问题是,我使用的是只读访问帐户,因此没有触发器或视图。这一定是选择查询的纯粹和简单。