访问多个所有者一条记录

时间:2012-09-25 16:53:11

标签: database ms-access ms-access-2007 relational-database

First Database具有以下内容:

OwnerID,FName,LName

第二个数据库具有以下内容:

OwnerID,PolicyName,Owner2ID,Owner3ID,Owner4ID,Owner5ID,Owner6ID,Owner7ID

因此,特定政策有多个所有者。我的问题是如何在Access中设计一个查询,该查询将返回具有多个所有者的每个策略的所有行。例如,假设策略1具有OwnerID,Owner2ID,Owner3ID,其基于第一数据库填充ID。我怎么能回来:

OwnerID,策略名称 Owner2ID,POlicy名称 Owner3ID,策略名称

同样的策略名称,但因为一个记录作为多个所有者,它将在查询中列出所有这些记录。

1 个答案:

答案 0 :(得分:0)

如果您首先对数据进行规范化,则可以运行任意数量的查询:

SELECT a.policyname,
   a.ownerid
FROM   (SELECT policyname,
           ownerid
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner2id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner3id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner4id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner5id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner6id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner7id
    FROM   policies) AS a; 

例如,这是一个计数:

SELECT a.policyname,
   Count(a.ownerid) AS CountOfOwnerID
FROM   (SELECT policyname,
           ownerid
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner2id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner3id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner4id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner5id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner6id
    FROM   policies
    UNION ALL
    SELECT policyname,
           owner7id
    FROM   policies) AS a
WHERE (((a.OwnerID) Is Not Null))
GROUP BY a.PolicyName;

您还可以保存“平面”查询并参考保存的查询来构建其他更复杂的查询。