Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Max() value of multiple parameters with additional limits

Tags:

sql

sql-server

I want to get the maximum value for each parameter, but within individual limits for each parameter. Here's the example table:

+-----------+------+------+------+
| VehicleID | Par1 | Par2 | Par3 |
+-----------+------+------+------+
|         1 |    6 | 9    | NULL |
|         2 |    7 | 7    | 1    |
|         3 |   10 | 3    | 2    |
|         1 |    8 | NULL | 7    |
|         2 |   10 | 1    | 6    |
|         3 |    6 | 8    | 9    |
|         1 |   10 | 4    | 11   |
|         2 |   11 | NULL | NULL |
|         3 |    3 | 6    | 12   |
+-----------+------+------+------+

The idea is to get the maximum value for Par1, Par2 and Par3 grouped per vehicleid but the maximum value should be below 9. If it's only for 1 parameter the query would be

select vehicleID, max(Par1) from Table1 where Par1<9 group by VehicleID

Is there a way to do this with 1 query, so the result should be:

+-----------+---------+---------+---------+
| VehicleID | MaxPar1 | MaxPar2 | MaxPar3 |
+-----------+---------+---------+---------+
|         1 |       8 |       4 |       7 |
|         2 |       7 |       7 |       6 |
|         3 |       6 |       8 |       2 |
|           |         |         |         |
+-----------+---------+---------+---------+

db<>fiddle

like image 547
ppetkov Avatar asked Sep 19 '26 02:09

ppetkov


1 Answers

Conditional aggregation is the simplest way to tackle this.

declare @Something table
(
    VehicleID int
    , Par1 int
    , Par2 int
    , Par3 int
)

insert @Something values
(1,  6, 9   , NULL)
, (2,  7, 7   , 1   )
, (3, 10, 3   , 2   )
, (1,  8, NULL, 7   )
, (2, 10, 1   , 6   )
, (3,  6, 8   , 9   )
, (1, 10, 4   , 11  )
, (2, 11, NULL, NULL)
, (3,  3, 6   , 12  )

select VehicleID
    , MaxPar1 = max(case when Par1 < 9 then Par1 end)
    , MaxPar2 = max(case when Par2 < 9 then Par2 end)
    , MaxPar3 = max(case when Par3 < 9 then Par3 end)
from @Something
group by VehicleID
like image 193
Sean Lange Avatar answered Sep 21 '26 17:09

Sean Lange



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!