Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL MAX(column) With Additional Criteria

Tags:

sql

sql-server

I have a single table, where I want to return a list of the MAX(id) GROUPed by another identifier. However I have a third column that, when it meets a certain criteria, "trumps" rows that don't meet that criteria.

Probably easier to explain with an example. Sample table has:

UniqueId (int) GroupId (int) IsPriority (bit)

Raw data:

UniqueId    GroupId    IsPriority
-----------------------------------
    1           1          F
    2           1          F
    3           1          F
    4           1          F
    5           1          F
    6           2          T
    7           2          T
    8           2          F
    9           2          F
   10           2          F

So, because no row in groupId 1 has IsPriority set, we return the highest UniqueId (5). Since groupId 2 has rows with IsPriority set, we return the highest UniqueId with that value (7).

So output would be:

5
7

I can think of ways to brute force this, but I am looking to see if I can do this in a single query.

like image 708
Phil Sandler Avatar asked Aug 11 '26 01:08

Phil Sandler


1 Answers

SQL Fiddle Demo

WITH T
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY GroupId 
                                    ORDER BY IsPriority DESC, UniqueId DESC ) AS RN
         FROM   YourTable)
SELECT UniqueId,
       GroupId,
       IsPriority
FROM   T
WHERE  RN = 1 
like image 57
Martin Smith Avatar answered Aug 13 '26 15:08

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!