Microsoft Access:每个公司选择一个电子邮件地址

时间:2018-10-29 16:17:06

标签: sql ms-access

我有一个与此表类似的表:

+---------+---------+-----------------+
| company |  type   |      email      |
+---------+---------+-----------------+
| ID001   | user    | user@email.com  |
| ID001   | admin   | admin@email.com |
| ID002   | user    | ...             |
| ID002   | admin   | ...             |
| ID002   | janitor | ...             |
| ID003   | admin   | ...             |
+---------+---------+-----------------+

我想SELECT type = user的所有电子邮件地址。如果user不存在,则应选择admin。如果还不存在,则应选择janitor,依此类推。

最后,我需要每个公司只有一个电子邮件地址的结果。我能够按type进行排序,然后像这样使用SELECT TOP 1

SELECT TOP 1
  contacts.company,
  contacts.type,
  contacts.email
FROM contacts
WHERE contacts.Email <> "" AND contacts.company = "ID001"
ORDER BY 
IIf([contacts.type] = 'user',1,
IIf([contacts.type] = 'admin',2,
IIf([contacts.type] = 'janitor',3,
4)))) ASC)

这仅适用于一个特定的公司,请参见WHERE条款。如何使它适用于整个桌子?

2 个答案:

答案 0 :(得分:1)

由于表contacts没有主键字段,因此可以使用以下内容:

SELECT
    t.company,
    t.type,
    t.email
FROM
    contacts t
WHERE
    t.company & t.type =
    (
        SELECT TOP 1 
            contacts.company & contacts.type
        FROM 
            contacts
        WHERE 
            contacts.Email IS NOT NULL AND contacts.company = t.company
        ORDER BY 
            IIf([contacts.type] = 'user',1,
            IIf([contacts.type] = 'admin',2,
            IIf([contacts.type] = 'janitor',3,
            4))) ASC
    )

这假定公司和类型的串联在数据集中将是唯一的。

答案 1 :(得分:1)

考虑嵌套IIF()的条件聚合查询:

SELECT c.company,
       MAX(IIF(c.type = 'user' AND c.Email IS NOT NULL, c.Type,
               IIF(c.type = 'admin' AND c.Email IS NOT NULL, c.Type,
                   IIF(c.type = 'janitor' AND c.Email IS NOT NULL, c.Type, NULL)
                  )
               )
          ) As final_type,
       MAX(IIF(c.type = 'user' AND c.Email IS NOT NULL, c.Email, 
               IIF(c.type = 'admin' AND c.Email IS NOT NULL, c.Email,
                   IIF(c.type = 'janitor' AND c.Email IS NOT NULL, c.Email, NULL)
                  )
               )
          ) As final_email
FROM contacts c
GROUP BY c.company