使用 sql 查询获取最新发布记录

Get latest release records using sql query

create table demo
(
    sno int primary key identity(1,1),
    cid int, 
    docno nvarchar(100),
    revisionid varchar(10) ,
    status nvarchar(100)
)

insert into demo 
values (1, 'abc', '00', 'release'),
       (2, 'abc', '01', 'release'),
       (3, 'abc', '02', 'notrelease'), 
       (4, 'xyz', '00', 'notrelease'),
       (5, 'xyz', '01', 'release'), 
       (6, 'xyz', '02', 'release'),
       (7, 'pqr', '01', 'release')

从下面table我想获取所有docno的最新发布状态的cid

例如:for abc ->cid=2,for xyz->cid=6,for abc ->pqr=7

sno cid Docno Revisionid status
1 1 abc 00 release
2 2 abc 01 release
3 3 abc 02 notrelease
4 4 xyz 00 notrelease
5 5 xyz 01 release
6 6 xyz 02 release
7 7 pqr 00 release

您可以使用以下查询获得所需的输出:

 select docno,max(cid) from Demo where status = 'release'
 group by docno;

使用子查询试试这个:

SELECT DISTINCT demo.docno, demo.cid
FROM demo
INNER JOIN 
(
  SELECT docno, max(Revisionid) as max_rev
  FROM demo
  WHERE status = 'release'
  GROUP BY docno
) as sq
ON demo.docno=sq.docno 
AND demo.Revisionid = sq.max_rev

db<>fiddle

在 Sql 服务器中,您可以将 TOP n WITH TIESROW_NUMBER 结合使用。

方便地获取每个文档的最新发布的 cid。

select top 1 with ties docno, cid
from demo
where status = 'release'
order by 
   row_number()
   over (partition by docno 
         order by cid desc, sno desc)
docno cid
abc 2
pqr 7
xyz 6

演示 db<>fiddle here