T-SQL如何提取记录的最大值

huangapple go评论59阅读模式
英文:

T-SQL How do I pull the max value of a record

问题

I apologize, but it seems you've requested not to answer translation-related questions. If you have any other non-translation questions or need assistance with something else, please feel free to ask.

英文:

I'm very new to T-SQL so sorry if this is not right.

Using T-SQL, how do I pull the max number from a record using 2 other columns? I have a unique ID number, visit number per ID and then the number of rooms that person have been to (Can do multiple rooms in one visit). How do I get it so that I can only select the row which has the highest number of Rooms a person visits using the persons ID and Visit Number?

Let's say I have this table;

T-SQL如何提取记录的最大值

What I want to have is just the rows with the highest Room number per ID and Visit_No. So with this table I would want to retrieve this dataset;

Dataset Wanted:

T-SQL如何提取记录的最大值

I thought using a ROW_SEQUENCE would work but I have tried but I don't think I am doing it correctly.

答案1

得分: 1

这可以使用 group bymax() 来完成:

首先根据ID和Visit No获取最新的Room_No

select ID, Visit_No, max(Room_No) as Room_No
from mytable
group by ID, Visit_No

然后使用 inner join 获取房间名称

select t.*
from mytable t
inner join (
  select ID, Visit_No, max(Room_No) as max_Room_No
  from mytable
  group by ID, Visit_No
) as s on s.ID = t.ID and s.Visit_No = t.Visit_No and s.max_Room_No = t.Room_No
英文:

This can be done using group by and max():

First get the latest Room_No per ID and Visit No

select ID, Visit_No, max(Room_No) as Room_No
from mytable
group by ID, Visit_No

Then get the room name using inner join

select t.*
from mytable t
inner join (
  select ID, Visit_No, max(Room_No) as max_Room_No
  from mytable
  group by ID, Visit_No
) as s on s.ID = t.ID and s.Visit_No = t.Visit_No and s.max_Room_No = t.Room_No

huangapple
  • 本文由 发表于 2023年5月25日 18:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定