[英]SQL Return MAX Values from Multiple Rows
I have tried many solutions and nothing seems to work. 我尝试了许多解决方案,但似乎没有任何效果。 I am trying to return the MAX status date for a project.
我正在尝试返回项目的MAX状态日期。 If that project has multiple items on the same date, then I need to return the MAX ID.
如果该项目在同一日期有多个项目,那么我需要返回MAX ID。 So far I have tried this:
到目前为止,我已经尝试过了:
SELECT PRJSTAT_ID, PRJSTAT_PRJA_ID, PRJSTAT_STATUS, PRJSTAT_DATE
From Project_Status
JOIN
(SELECT MAX(PRJSTAT_PRJA_ID) as MaxID, MAX(PRJSTAT_DATE) as MaxDate
FROM Project_Status
Group by PRJSTAT_PRJA_ID)
On
PRJSTAT_PRJA_ID = MaxID and PRJSTAT_DATE = MaxDate
Order by PRJSTAT_PRJA_ID
It returns the following: 它返回以下内容:
I am getting multiple records for PRJSTAT_PRJA_ID, but I only want to return the row with the MAX PRJSTAT_ID. 我正在获得PRJSTAT_PRJA_ID的多个记录,但是我只想返回具有最大PRJSTAT_ID的行。 Any thoughts?
有什么想法吗?
Take out the MAX on the ID on the subquery: 在子查询的ID上取出MAX:
SELECT PRJSTAT_ID, PRJSTAT_PRJA_ID, PRJSTAT_STATUS, PRJSTAT_DATE
From Project_Status
JOIN
(SELECT PRJSTAT_PRJA_ID as ID, MAX(PRJSTAT_DATE) as MaxDate
FROM Project_Status
Group by PRJSTAT_PRJA_ID)
On
PRJSTAT_PRJA_ID = ID and PRJSTAT_DATE = MaxDate
Order by PRJSTAT_PRJA_ID
Or remove the need to join: 或无需加入:
SELECT * FROM
(SELECT PRJSTAT_ID, PRJSTAT_PRJA_ID, PRJSTAT_STATUS, PRJSTAT_DATE,
ROW_NUMBER() OVER (PARTITION BY PRJSTAT_PRJA_ID ORDER BY PRJSTAT_DATE DESC)
AS SEQ,
ROW_NUMBER() OVER (PARTITION BY PRJSTAT_PRJA_ID ORDER BY PRJSTAT_PRJA_ID
DESC) AS IDSEQ
From Project_Status
)PR
WHERE SEQ = 1
AND IDSEQ = 1
Your problem is ties. 你的问题是关系。 You want the record with the maximum date per
PRJSTAT_PRJA_ID
and in case of a tie the record with the highest ID. 您想要每个
PRJSTAT_PRJA_ID
具有最长日期的记录,并且如果出现平局,则ID最高的记录。 The easiest way to rank records per group and only keep the best record is ROW_NUMBER
: 对每个组的记录进行排名并仅保持最佳记录的最简单方法是
ROW_NUMBER
:
select prjstat_id, prjstat_prja_id, prjstat_status, prjstat_date
from
(
select
project_status.*,
row_number() over (partition by prjstat_prja_id
order by prjstat_date desc, prjstat_id desc) as rn
from project_status
)
where rn = 1
order by prjstat_prja_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.