具有附加限制的多个参数的SQL Server Max()值

时间:2019-03-06 14:33:09

标签: sql sql-server

我想获得每个参数的最大值,但要在每个参数的单独限制内。这是示例表:

+-----------+------+------+------+
| 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   |
+-----------+------+------+------+

该想法是获取按每个车辆ID分组的Par1,Par2和Par3的最大值,但最大值应低于9。 如果仅用于1个参数,查询将为

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

是否可以通过1个查询来执行此操作,所以结果应该是:

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

db<>fiddle

1 个答案:

答案 0 :(得分:6)

有条件聚合是解决此问题的最简单方法。

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