0

I need to create a MS Access query that will return only one instance of a serial number along with a few other columns. For example

SerialNumber    CRM        EmailClient   VersionBuild  IPAddress  DateLogged
------------    ----       -----------   ------------  ---------  ----------
123456          Outlook    Outlook       4.7.4         0.0.0.0    20120625
123456          SugarCRM   SMTP          4.6.1         0.0.0.0    20120621
435352          ACT!       Outlook       4.5.2         0.0.0.0    20120619
537352          ACT!       SMTP          4.5.3         0.0.0.0    20120619

The results would be

SerialNumber    CRM        EmailClient   VersionBuild  IPAddress  DateLogged
------------    ----       -----------   ------------  ---------  ----------
123456          Outlook    Outlook       4.7.4         0.0.0.0    20120625
435352          ACT!       Outlook       4.5.2         0.0.0.0    20120619
537352          ACT!       SMTP          4.5.3         0.0.0.0    20120619

I was trying to complete this using the following query. I think First and Group by cancel each other out.

SELECT FIRST(LogData.SerialNumber), LogData.CRM, LogData.EmailClient, LogData.VersionBuild, LogData.IPAddress, LogData.DateLogged
FROM LogData
GROUP BY  LogData.CRM, LogData.EmailClient, LogData.VersionBuild, LogData.IPAddress, LogData.DateLogged
4

3 回答 3

1

在您提到的评论中 LogData 没有主键。如果您添加自动编号主键,您的问题将变得非常容易解决。

使用子查询为每个组返回一个id值,子查询为.SerialNumberINNER JOINLogData

SELECT base.*
FROM
    LogData AS base
    INNER JOIN (
        SELECT SerialNumber, Min(id) AS which_id
        FROM LogData
        GROUP BY SerialNumber
    ) AS sub
    ON base.id = sub.which_id;

替换base.*为要显示的字段列表。

于 2012-07-19T15:47:42.003 回答
0

这不漂亮但是...

SELECT L.SerialNumber, 
            (Select Top 1 A.First from LogData as A where A.SerialNumber = L.SerialNumber Order by A.First, A.Last) AS [First], 
            (Select Top 1 A.Last from LogData as A where A.SerialNumber = L.SerialNumber Order by A.First, A.Last) AS [Last]
FROM LogData AS L
GROUP BY L.SerialNumber;

这基本上是 Thomas 的回答,除了因为您使用的是子查询,您可以指定 order by 以确保您始终获得预期的结果。

于 2012-07-19T14:39:08.213 回答
0

我想你想这样做:

  • 只得到一个 SerialNumber => GROUP BY SerialNumber
  • 为每个 SerialNumber => FIRST(LogData.First) 只获取一个(第一个)名称
选择 LogData.SerialNumber,FIRST(LogData.First),FIRST(LogData.Last)
来自日志数据
按 LogData.SerialNumber 分组

但请注意:这可能会导致(不是在“FIRST”函数的情况下)混合记录,例如:

序号 前 后
------ ----- ----
123456 弗兰克·史密斯

顺便说一句:并非所有 SQL 系统都支持“FIRST”-Grouping-Function:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html 可以使用另一个满足sql标准的功能...

于 2012-07-19T13:38:14.407 回答