根据不同的列选择最大值

时间:2019-10-31 15:56:25

标签: sql sql-server

我正试图从另一列中获得最高价值。

SELECT DISTINCT 
    AppDetailVehicleValuation.AppID, 
    VehicleValuationOption.Description, 
    MAX (VehicleValuationOptionValueType.Value)
FROM            
    AppDetailVehicleValuation
    INNER JOIN VehicleValuationOption 
        ON AppDetailVehicleValuation.ValuationID = VehicleValuationOption.ValuationID 
    INNER JOIN VehicleValuationOptionValueType 
        ON VehicleValuationOption.ValuationOptionID = VehicleValuationOptionValueType.ValuationOptionID
WHERE        
    (VehicleValuationOption.IsSelected LIKE '1') 
    AND (VehicleValuationOption.IsSystemOption LIKE '1')

我有这个

AppID | Description | Value
999     Beats Audio   425.00
999     Beats Audio   475.00
999     Power Str.    600.00
999     Power Str.    750.00

这就是我需要的

AppID | Description | Value
999     Beats Audio   475.00
999     Power Str.  | 750.00

3 个答案:

答案 0 :(得分:1)

您可以简单地执行以下操作:

 SELECT
       t.AppId, 
       t.Description, 
       max(t.Value)
 FROM mytable t
 GROUP BY t.description, t.AppId

答案 1 :(得分:1)

您只是在查询中缺少GROUP BY子句:

SELECT
    AppDetailVehicleValuation.AppID, 
    VehicleValuationOption.Description, 
    MAX (VehicleValuationOptionValueType.Value)
FROM            
    AppDetailVehicleValuation
    INNER JOIN VehicleValuationOption 
        ON AppDetailVehicleValuation.ValuationID = VehicleValuationOption.ValuationID 
    INNER JOIN VehicleValuationOptionValueType 
        ON VehicleValuationOption.ValuationOptionID = VehicleValuationOptionValueType.ValuationOptionID
WHERE        
    (VehicleValuationOption.IsSelected LIKE '1') 
    AND (VehicleValuationOption.IsSystemOption LIKE '1')
GROUP BY AppDetailVehicleValuation.AppID, VehicleValuationOption.Description

答案 2 :(得分:0)

这个评论太长了。

很高兴您找到了与GROUP BY一起使用的答案。我建议您开始在查询中使用别名。它可以快速轻松地将一堵墙变成很容易看到的事情。您可能会遵循以下原则结束

SELECT advv.AppID
    , vvo.Description
    , MaxValue = MAX(vvot.Value)
FROM AppDetailVehicleValuation advv
INNER JOIN VehicleValuationOption vvo ON advv.ValuationID = vvo.ValuationID 
INNER JOIN VehicleValuationOptionValueType vvot ON vvo.ValuationOptionID = vvot.ValuationOptionID
WHERE vvo.IsSelected = '1'
    AND vvo.IsSystemOption = '1'
group by advv.AppID
    , vvo.Description