我有这样的学生表:
最初在版本0中有2条记录。每当我在记录中进行任何更改时,它总是在表中创建具有新记录ID但同样是student_id和新版本的新条目。这是为了版本管理和数据回溯。
现在我运行查询以获取版本0的数据:
SELECT * FROM tblStudent as a
inner join (
select student_id, max(record_id) as MaxRecordID from tblStudent group by student_id
) b on a.student_id=b.student_id and a.record_id = MaxRecordID
where a.version=0
由于最新的reocord将具有最大record_id
所以我按student_id
进行分组,并且只获得具有最大record_id的记录。
但它给我错误的输出。问题是我不能在内部联接查询中编写version=0
条件而group by student_id。
答案 0 :(得分:0)
这就是我所做的。我假设您将该版本作为参数传递给查询。
create table #temp1(
recordid int,
student_id int,
student_name varchar(5),
version int
)
insert into #temp1
values(1,1,'aaa',0)
insert into #temp1
values(2,2,'bbb',0)
insert into #temp1
values(3,3,'ccc',0)
insert into #temp1
values(4,1,'aa1',1)
insert into #temp1
values(5,1,'aa2',1)
declare @version int = 0;
with cte (recordid, student_id)
as (select max(recordid) , student_id
from #temp1
where version <= @version group by student_id
)
select cte.recordId, t.student_id, t.version, t.student_name
from cte
inner join #temp1 t on t.recordid = cte.recordid
答案 1 :(得分:0)
您可以使用row_number() over ( partion by Student_Id order by version)
。
见example
CREATE TABLE tblStudent(Record_Id INT, Student_Id INT, Student_Name nvarchar(50) , Version INT)
INSERT INTO tblStudent(Record_Id, Student_Id, Student_Name, Version)
VALUES
(1,1,'aaa',0),
(2, 2, 'bbb', 0),
(3,3,'aaa',0),
(4,1,'aa1',1),
(5,1,'aa2',2)
SELECT *
FROM (
SELECT *, Row_Number() OVER (PARTITION BY Student_Id ORDER BY Version ASC) Ranking
FROM tblStudent
) sub
WHERE sub.Ranking = 1
应该更改选择*
如果您想要最新版本,可以使用DESC
代替ASC
。检查执行计划,根据排序添加正确的索引。
答案 2 :(得分:0)
一种非常简单的方法:
create table #t (record_id int, student_id int, student_name varchar(50), version int)
insert into #t values
(1,1,'aaa',0),
(2,2,'bbb',0),
(3,3,'ccc',0),
(4,1,'aa1',1),
(5,1,'aa2',1)
select * from #t
declare @ver int;
set @ver = 1; --configurable as 0 or 1
SELECT a.* FROM #t as a
inner join (
select student_id, max(record_id) as MaxRecordID from #t group by student_id
) b on a.student_id=b.student_id
where (
(@ver = 1 and (a.record_id = b.MaxRecordID))
or
(@ver = 0) and (a.version = 0)
)
order by a.student_id
用tblStudent替换#t