0

I'm trying to create a query to return the file with the max version, independent of the value of the server. How could I do that?

actual table data:

server    filename    v4    date
local     code1.zip   41    0000-00-00
remote    code1.zip   39    0000-00-00
local     code1.zip   28    0000-00-00
remote    code1.zip   21    0000-00-00
local     code1.zip   32    0000-00-00
remote    code1.zip   27    0000-00-00

the query:

SELECT
    server,
    filename,
    max(v4) as v4,
    date
FROM
    table
WHERE
    date ='0000-00-00'

GROUP BY
    filename,
    server,
    date

Actual result:

server    filename    v4    date
local     code1.zip   41    0000-00-00
remote    code1.zip   39    0000-00-00

Expected result:

server    filename    v4    date
local     code1.zip   41    0000-00-00

EDIT: It's for MySQL

Thanks in advance.

2
  • Try this GROUP BY date only Jan 20, 2014 at 18:22
  • ORDER BY something LIMIT 1
    – Strawberry
    Jan 20, 2014 at 19:14

3 Answers 3

4

If you just want the row with largest v4 you can use this

SELECT
    server,
    filename,
    v4,
    date
FROM
    `table`
WHERE
    date ='0000-00-00'
ORDER BY v4 DESC
LIMIT 1

to get max V4 for each filename, first you get max(v4) group by filename then INNER JOIN back with table like below

SELECT T1.server,T1.filename,T1.v4,T1.date
FROM
`table` T1 INNER JOIN
    (SELECT filename,max(v4) as maxv4
     FROM `table`
     WHERE date = '0000-00-00'
     GROUP BY filename)T2
ON T1.filename = T2.filename AND T1.v4 = T2.maxV4
WHERE date = '0000-00-00';
2
  • @TinTran and if i have more than one code? for example, code1.zip, code2.zip ? I know its not marked on the question, but could you please give an example about if have more? =) thanks!
    – thclpr
    Jan 20, 2014 at 18:31
  • updated my answer for you to grab max(v4) for each filename(code1.zip,code2.zip).
    – Tin Tran
    Jan 20, 2014 at 18:38
1

To get the the max version you only have to do:

SELECT MAX(version) FROM table 

If you also want the filename (if you have another column id):

SELECT t2.filename, t2.maxver
FROM table t1 INNER JOIN
(SELECT id, MAX(version) maxver 
FROM table 
GROUP BY id) t2 ON t1.id=t2.id
ORDER BY t2.maxver DESC
LIMIT 1

If you also want the filename (if you haven't another column id, use filename):

SELECT t2.filename, t2.maxver 
FROM table t1 INNER JOIN
     (SELECT filename, MAX(version) maxver 
      FROM table 
      GROUP BY filename) t2 ON t1.filename=t2.filename
      WHERE t2.maxver = (SELECT MAX(version) FROM table)

There are many ways to do it.

0

You could use this query:

Select Top 1 *
From table
Where v4 = (
SELECT
    max(v4) as v4,
FROM
    table
WHERE
    date ='0000-00-00'

GROUP BY
    v4
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.