示例表:
id computer app version build date
---|---------|------|------------|-------|---------
1 | aaaa1 | app1 | 1.0.0 | 1 | 2013-11-11 09:51:07
2 | aaaa1 | app2 | 2.0.0 | 2 | 2013-11-12 09:51:07
5 | xxxx2 | app1 | 1.0.0 | 1 | 2013-11-13 09:51:07
3 | cccc3 | app2 | 3.1.0 | 1 | 2013-11-14 09:51:07
4 | xxxx2 | app1 | 1.0.0 | 2 | 2013-11-15 09:51:07
5 | cccc3 | app2 | 3.1.1 | 3 | 2013-11-16 09:51:07
6 | xxxx2 | app1 | 1.0.2 | 1 | 2013-11-17 09:51:07
7 | aaaa1 | app1 | 1.0.2 | 3 | 2013-11-18 09:51:07
所需的输出(不是确切的格式或列表顺序),在每台计算机上获取每个应用的最新安装:
7. aaaa1 - app1 - 1.0.2 - 3 - 2013-11-18 09:51:07
2. aaaa1 - app2 - 2.0.0 - 2 - 2013-11-12 09:51:07
6. xxxx2 - app1 - 1.0.2 - 1 - 2013-11-17 09:51:07
5. cccc3 - app2 - 3.1.1 - 3 - 2013-11-16 09:51:07
我的SQL声明:
SELECT
id,
computer,
app,
version,
build,
MAX(date) AS installed
FROM
data
WHERE
placement = 'xxx'
GROUP BY
app, computer
;
这给了我:
1. aaaa1 - app1 - 1.0.0 - 1 - 2013-11-11 09:51:07
而不是
7. aaaa1 - app1 - 1.0.2 - 3 - 2013-11-18 09:51:07
正如我所料。
MAX(日期)如果我仅选择MAX(日期),则无效。但是我没有得到任何数据(只是最新日期)。
SELECT
MAX(date) AS installed
我不是一个SQL忍者,所以我很快会因为这个而挠头。
答案 0 :(得分:10)
试试这样:
SELECT d.id, d.computer, d.app, d.version, d.build, a.installed
FROM data d
INNER JOIN (
SELECT computer, app, max(DATE) AS installed
FROM data
GROUP BY computer, app
) a ON a.computer = d.computer AND a.app = d.app
WHERE placement = 'xxx'
内部查询为您提供每对计算机和应用程序的最大值(日期),然后您只需加入其中以获取其余信息。
答案 1 :(得分:5)
尝试投射日期时间字段
SELECT
id,
computer,
app,
version,
build,
MAX(cast(date as Datetime)) AS installed
FROM
data
WHERE
placement = 'xxx'
GROUP BY
app, computer, id, version, build
;
答案 2 :(得分:0)
max - 是一个聚合函数,尝试将select语句中的所有列添加到GROUP BY
:
GROUP BY
app, computer, id, version, build.
答案 3 :(得分:0)
这可能是因为您将日期存储为String,并且比较字符串的行为与比较整数不同。您应该以 unix时间戳格式存储日期,并且它们将更容易比较。但是需要额外的努力才能显示为正常的英语日期。
答案 4 :(得分:0)
错误:
SELECT
id,
computer,
app,
version,
build,
`date` AS installed
FROM
data
WHERE
placement = 'xxx'
ORDER BY installed DESC
GROUP BY app;
答案 5 :(得分:0)
MAX不适用于我,有效的是我按日期对表进行了预排序的其他子查询:
SELECT d.id, d.computer, d.app, d.version, d.build, a.installed
FROM data d
INNER JOIN (
SELECT computer, app, date as installed
FROM (
SELECT computer, app, date
FROM data
ORDER BY date desc
) as t
GROUP BY computer, app
) a ON a.computer = d.computer AND a.app = d.app
WHERE placement = 'xxx'