Home > Blockchain >  Group by row but give highest value of other row
Group by row but give highest value of other row

Time:11-16

Query:

SELECT
    ID, Name, Component, Version 
FROM
    modules 
WHERE 
    modules.ValidTo > NOW() AND modules.ValidFrom < Now();

returns:

ID Name Component Version
12 TC1 a 1.0.0
13 TC2 b 1.0.0
15 TC3 c 1.2.0
17 TC3 c 1.2.5

Desired data (group by Component but return record with highest Version):

ID Name Component Version
12 TC1 a 1.0.0
13 TC2 b 1.0.0
17 TC3 c 1.2.5

I have tried this query

SELECT
    modules.ID, modules.Name, modules.ComponentIdentifier,
    EXEName, MAX(Version)
FROM
    modules
WHERE 
    modules.ValidTo > NOW() AND modules.ValidFrom < Now()
GROUP BY
    modules.ComponentIdentifier;

But it returns the wrong ID. I would need the ID 17 not 15.

ID Name Component Version
12 TC1 a 1.0.0
13 TC2 b 1.0.0
15 TC3 c 1.2.5

How to solve this?

CodePudding user response:

You are using group by in improper way .. normally the select for not aggregated column not mention in group by is not allowed . in some db this allowed (mysql versione <5.7 or with ONLY_FULL_GROUP_BY disabled) but produce impredictable result
then if you can't add aggregation function to the column not mendtiond in group by
you need subquery for filter the correct value

select modules.ID, modules.Name, modules.ComponentIdentifier,
    EXEName, a.max_ver 
from  (
    SELECT
    modules.ComponentIdentifier,
     MAX(Version) max_ver
    FROM   modules
    WHERE  modules.ValidTo > NOW() AND modules.ValidFrom < Now()
    GROUP BY  modules.ComponentIdentifie
    ) a 
INNER JOIN  modules on modules.ComponentIdentifier = a.ComponentIdentifier 
   and a.max_ver= modules.Version
  •  Tags:  
  • sql
  • Related