简体   繁体   English

SQL 服务器:来自子查询的最大值

[英]SQL Server : max value from sub query

Please help me with retrieve max values.请帮助我检索最大值。 I've created a few simple tables.我创建了一些简单的表格。 The first one is users the second one is books.第一个是用户,第二个是书籍。 So i need to use sub query to retrieve the the names of the books which date of taking by user is the latest所以我需要使用子查询来检索用户使用日期最新的书籍名称

Here are the tables:以下是表格:

CREATE TABLE book_base 
(
    book_id int,
    user_id int,
    title VARCHAR(20),
    date DATE,
); 

CREATE TABLE users 
(
    userid int,
    name VARCHAR(20),
); 

INSERT INTO book_base (book_id, user_id, title, date)
VALUES ('221', 1, 'Just book', '2021-2-2'),
       ('222', 1, 'The book', '2020-4-8'),
       ('223', 1, 'My book', '2019-8-8'),
       ('228', 2, 'Nice book', '2021-1-2'),
       ('225', 2, 'Coole book', '2020-4-8'),
       ('226', 2, 'Super book', '2019-9-8');

INSERT INTO users (userid, name) 
VALUES ('1', 'John Smith'),
       ('2', 'Mary Adams');

And I've tried to do like this我试过这样做

SELECT
    userid AS [UID], 
    name AS [UserName], 
    bb.title, bb.date 
FROM
    users u
JOIN 
    (SELECT user_id title, MAX(date) 
     FROM book_base) bb ON u.userid = bb.user_id

The result should be just the rows there date is max date结果应该只是日期为最大日期的行

假设结果

Try this, it's based on the data you privided:试试这个,它基于您提供的数据:

SELECT *
FROM users u
JOIN (
  select user_id,MAX(date) as DATE 
  from book_base GROUP BY user_id
) bb ON u.userid = bb.user_id
JOIN book_base b ON u.userid = b.user_id
AND bb.date = b.date

You can use Cross Apply with a subquery that uses Top 1 With Ties .您可以将Cross Apply与使用Top 1 With Ties的子查询一起使用。

Select u.userid As [UID], u.name As [UserName], bb.title, bb.date 
From users u Cross Apply 
    (Select Top 1 With Ties user_id, title, date 
     From book_base
     Where user_id=u.userid 
     Order by date Desc) As bb

Using a correlated subquery to filter by max date使用相关子查询按最大日期过滤

select b1.*, u.name
from book_base b1
join users u on u.userid = b1.user_id
where date = (select max(b2.date) 
             from book_base b2 
             where b2.user_id = b1.user_id)
Select * from (
 SELECT
  userid AS [UID], 
  [name] AS [UserName], 
bb.title, Rank() OVER (Partition By bb.[user_id] order by bb.[date] desc) r,bb.[date]
FROM
users u inner join book_base bb ON u.userid = bb.[user_id]
) t
where r=1

Check if it helps,看看有没有帮助

If you remove outer select you will find why this work,如果您删除外部 select 您会发现为什么会这样,

Rank is a built in function, it ranks all data by first partitioning it in groups and ordering as given then you can filter result as you need, Rank 是内置的 function,它通过首先将所有数据分组并按照给定的顺序排列所有数据,然后您可以根据需要过滤结果,

For example r=2 will provide second most recent date.例如 r=2 将提供第二个最近的日期。 and r=1 is top 1 record from each group并且 r=1 是每组的前 1 条记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM