简体   繁体   中英

Select rows using group by and in each group get column values based on highest of another column value

I need to get latest field based on another field in group by we have

Table "SchoolReview"

Id SchoolId Review Point
1 1 rv1 8
2 1 rv2 7
3 2 rv3 4
4 2 rv4 7
5 3 rv5 2
6 3 rv6 8

I need to group by SchoolId and the inside group I need to get Review and Point from highest "Id" column.

I dont need "Id" coulmn but even if I get it for this solution its okay.

Result I am looking for shall look like this.

SchoolId Review Point
1 rv2 7
2 rv4 7
3 rv6 8

Any one experienced in MS SQL Server can help in this regard?

You do not need to group the rows, you simply need to select the appropriate rows from the table. In this case, using ROW_NUMBER() is an option:

Table:

SELECT *
INTO Data
FROM (VALUES
   (1, 1, 'rv1', 8),
   (2, 1, 'rv2', 7),
   (3, 2, 'rv3', 4),
   (4, 2, 'rv4', 7),
   (5, 3, 'rv5', 2),
   (6, 3, 'rv6', 8)
) v (Id, SchoolId, Review, Point)

Statement:

SELECT SchoolId, Review, Point
FROM (
   SELECT *, ROW_NUMBER() OVER (PARTITION BY SchoolId ORDER BY Id DESC) AS Rn
   FROM Data
) t
WHERE Rn = 1

Result:

SchoolId Review Point
---------------------
1        rv2    7
2        rv4    7
3        rv6    8

Using sample data from other answer

SELECT *
INTO #Data
FROM (VALUES
   (1, 1, 'rv1', 8),
   (2, 1, 'rv2', 7),
   (3, 2, 'rv3', 4),
   (4, 2, 'rv4', 7),
   (5, 3, 'rv5', 2),
   (6, 3, 'rv6', 8)
) v (Id, SchoolId, Review, Point)

SELECT S.SchoolId,
       S.Review,
       S.Point 
FROM   #Data S
INNER JOIN
(
    SELECT Id = MAX(S1.Id),
           S1.SchoolId
    FROM   #Data S1
    GROUP BY SchoolId
) X ON X.Id = S.Id AND X.schoolId = S.SchoolId
ORDER BY X.SchoolId    
;

output

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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