按日期和版本选择最后一条记录

时间:2018-12-13 11:28:21

标签: sql sql-server

我具有以下表格结构:

here is the screenshot

我正在尝试获取每个代码的最新记录,日期类型和基于版本的详细信息。

我尝试了group by,但无法使用MAX函数,但是只能给我每个版本的最大值。

我正在使用SQLServer数据库。

4 个答案:

答案 0 :(得分:0)

使用row_number()

select * from 
(
select *, row_number() over(partition by Code order by date desc) rn
from table
) t where t.rn=1

答案 1 :(得分:0)

使用row_number,您可以实现这一目标。

select * from 
(
select *, row_number() over(partition by Code order by version desc) rn
from table
) x where x.rn=1

答案 2 :(得分:0)

简介

由于我不太确定OP的用途,因此我提出了三个不同的答案。例如,尚不清楚在group-by语句中将使用哪些colulmn,或者他们是否希望每天或所有数据确定代码。

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=cb3424696dcc71225e14f1bb16dc1a7c

create table data(
code varchar(20),
date integer,
version int,
type varchar(20),
details varchar(20)); 

insert into data values ('x121',01022018, 1, 'r','SOME DETAILS');
insert into data values ('x121',01022018, 3, 'r','SOME DETAILS');
insert into data values ('x121',01022018, 2, 'r','MORE DETAILS');

insert into data values ('x22',01022018, 1, 'b','SOME DETAILS');
insert into data values ('x64',01022018, 2, 't','SOME DETAILS');

insert into data values ('x121',01012018, 1, 'r','SOME DETAILS');
insert into data values ('x121',01012018, 2, 'r','SOME DETAILS');

1)在原始数据和“最高版本”列表之间进行联接

select '1) Join between original data and list of Max Versions';

select  d.code, d.date, d.version, d.type, d.details from
(select code, max(version) as maxVersion from data
group by code) maxVersions,
data d
where d.version = maxVersions.maxVersion and d.code = maxVersions.code;

2)首先尝试在有条件的地方使用嵌套查询

select '2) First try using nested query in where condition';

SELECT t.code, t.date, t.version, t.type, t.details
FROM data t
WHERE VERSION =
    (SELECT max(VERSION)
     FROM data t2
     WHERE t2.Code = t.Code
       AND t2.Date = t.Date
       AND t2.type = t.type)
;

3)按每个代码,日期类型和详细信息分组

select '3) Grouping by each code, date type and details ';

select  d.code, d.date, d.version, d.type, d.details from
(select code, type, details, max(version) as maxVersion from data
group by code, type, details) maxVersions,
data d
where d.version = maxVersions.maxVersion and d.code = maxVersions.code
order by d.date desc;

答案 3 :(得分:0)

尝试一下-

select * from 
(
select *, row_number() over(partition by Code, [type] order by [Date],[Version] desc) rn
from #Codedetails
) x where x.rn=1