表格示例:
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(date),而没有其他选择,则MAX(date)有效。但是,那时我没有任何数据可以使用(仅是最新日期)。
SELECT MAX(date) AS installed
我不是SQL忍者,所以我很快就会因此而挠头。
尝试这样:
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'
内部查询是为您获取每对计算机和应用程序的max(date)最大值,然后您只需与之结合即可获取其余信息。