我想确定关于特定月份的变量的最后状态。例如
Variable Date Operation State
A 01Jan2019 1 10
A 10Jan2019 3 20
A 31Jan2019 4 50
A 05Feb2019 7 60
A 22Feb2019 8 70
B 06Jan2019 2 10
B 07Jan2019 3 20
B 07Feb2019 6 60
B 15Mar2019 9 80
结果应该喜欢
Variable Month Year Last_State_Until_End_of_Month
A 1 2019 50
A 2 2019 70
A 3 2019 70
B 1 2019 20
B 2 2019 60
B 3 2019 80
请注意,对于三月份的变量A,最后一个状态与二月份相同。 (3月未进行任何更改)。我不知道是否有帮助,但是有一个操作ID会随着状态的每次更改而增加,而与变量的选择无关。
答案 0 :(得分:0)
感谢Panagiotis Kanavos以下查询的工作原理:
declare @table_test TABLE (variable_name nvarchar(255), date_var date, op_id int, state int)
insert into @table_test Values
('A', '01Jan2019', 1 ,10),
('A', '10Jan2019', 3 ,20),
('A', '31Jan2019', 4 ,50),
('A', '05Feb2019', 7 ,60),
('A', '22Feb2019', 8 ,70),
('B', '06Jan2019', 2 ,10),
('B', '07Jan2019', 3 ,20),
('B', '07Feb2019', 6 ,60),
('B', '15Mar2019', 9 ,80)
select
year(date_var) as year
,month(date_var) as month
,variable_name,
,Last_value(State) OVER (partition by year(date_var),month(date_var),variable_name order by date_var ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_value
from @table_test
Order by variable_name, year(date_var),month(date_var)
此查询返回:
year month variable_name last_value
2019 1 A 50
2019 1 A 50
2019 1 A 50
2019 2 A 70
2019 2 A 70
2019 1 B 20
2019 1 B 20
2019 2 B 60
2019 3 B 80