从查询返回最大值

时间:2014-01-20 18:19:29

标签: mysql sql select aggregate-functions

我正在尝试创建一个查询以使用max版本返回文件,而与服务器的值无关。我怎么能这样做?

实际表格数据:

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

查询:

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

GROUP BY
    filename,
    server,
    date

实际结果:

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

预期结果:

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

编辑:这是 MySQL

提前致谢。

3 个答案:

答案 0 :(得分:4)

如果您只想要具有最大v4的行,则可以使用此

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

为每个文件名获取最大V4,首先按文件名获取max(v4)组,然后使用table将INNER JOIN返回到下面

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';

答案 1 :(得分:1)

要获得最高版本,您只需要这样做:

SELECT MAX(version) FROM table 

如果您还想要文件名(如果您有另一列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

如果您还想要文件名(如果您没有其他列id,请使用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)

有很多方法可以做到。

答案 2 :(得分:0)

您可以使用此查询:

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

GROUP BY
    v4
)