[英]A query that shows latest published books from each publisher from a table
I'm trying to write a query that show latest published books from each publisher from a table like this我正在尝试编写一个查询,从这样的表中显示每个出版商的最新出版书籍
bookcode![]() |
Name![]() |
Publisher![]() |
PublishYr![]() |
---|---|---|---|
61523 ![]() |
c++![]() |
Pearson![]() |
2018 ![]() |
54681 ![]() |
python ![]() |
sybex ![]() |
2017 ![]() |
45168 ![]() |
sql ![]() |
RELX![]() |
2019 ![]() |
79137 ![]() |
c# ![]() |
Macmillan![]() |
2016 ![]() |
89451 ![]() |
ccna![]() |
Pearson![]() |
2020 ![]() |
45187 ![]() |
lpic 1![]() |
RELX![]() |
2021 ![]() |
16497 ![]() |
ccnp![]() |
sybex ![]() |
2018 ![]() |
19437 ![]() |
lpic 2![]() |
Penguin![]() |
2019 ![]() |
and desired table in query should be:查询中所需的表应该是:
Publisher![]() |
name![]() |
---|---|
Pearson![]() |
ccna![]() |
sybex ![]() |
ccnp![]() |
RELX![]() |
lpic 1![]() |
Macmillan![]() |
c# ![]() |
Penguin![]() |
lpic 2![]() |
Here is one way using window functions:这是使用窗口函数的一种方法:
select * from (
select * , row_number() over (partition by publisher order by PublishYr desc) rn
from tablename
) t where rn = 1
The query doesn't need a subquery if you use SELECT TOP(1) WITH TIES
.如果您使用
SELECT TOP(1) WITH TIES
则查询不需要子查询。
select top(1) with ties publisher, book_name,
row_number() over (partition by Publisher
order by PublishYr desc) rn
from TableWithData
order by rn;
Get maximum year per publisher as subquery and join with source table.获取每个发布者的最大年份作为子查询并加入源表。
Select tablename.Publisher, tablename.Name
From tablename
Inner Join (
Select max(PublishYr) As MaxPublishYr, Publisher
From tablename
Group By Publisher
) as Subqry on Subqry.Publisher = tablename.Publisher
and Subqry.MaxPublishYr = tablename.PublishYr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.