【问题标题】:MS Access output duplicate rows on joined tablesMS Access 在连接表上输出重复行
【发布时间】:2015-07-27 11:02:49
【问题描述】:

我一直在努力解决这个问题。

我有一个访问数据库。它有 3 个导入的表。 一个表是第一列中业务服务类型的完整列表,例如 A、B、C、D。
其他 2 个表代表一年中的月份,例如“Jan Bus All”和“Feb Bus All”。这两个在 A 列中包含业务服务类型,在 B 列中包含该服务类型已使用的月份的计数。

我将 2 个月的表连接到服务类型表,将连接放在 A 列,即业务服务类型。 每个月可能使用不同的服务类型。例如,一月可能有 A 和 C 的计数。二月可能有 A 和 D。

问题是,我希望在输出中获得与服务类型列表相对应的不同行,但是我得到了服务类型的多行,每个月都有交替计数。

我错过了什么吗?

这是 Access 中使用的 SQL 代码。

 SELECT DISTINCT [Business Service Type List].[Bus Service] AS Business_Service,   
[Jan Bus All].Jan AS Jan, [Feb Bus All].Feb AS Feb  
    FROM [Feb Bus All]   
RIGHT JOIN ([Jan Bus All] RIGHT JOIN [Business Service Type List]   
ON [Jan Bus All].Business_Service = [Business Service Type List].[Bus Service])  
ON [Feb Bus All].Business_Service = [Business Service Type List].[Bus Service]   
GROUP BY [Business Service Type List].[Bus Service], [Jan Bus All].Jan, [Feb Bus All].Feb;

【问题讨论】:

    标签: sql ms-access


    【解决方案1】:

    您的版本对我来说很好,下面的这个也是。

    SELECT DISTINCT [Business Service Type List].[Bus Service] AS Business_Service, 
       [Jan Bus All].Jan AS Jan, [Feb Bus All].Feb AS Feb
    FROM [Feb Bus All] RIGHT JOIN ([Jan Bus All] 
    RIGHT JOIN [Business Service Type List] 
       ON [Jan Bus All].Business_Service = [Business Service Type List].[Bus Service]) 
       ON [Feb Bus All].Business_Service = [Business Service Type List].[Bus Service]
    WHERE [Jan Bus All].Jan Is Not Null OR [Feb Bus All].Feb Is Not Null;
    

    我认为这意味着您的一张表中有重复值。换句话说,在您的二月表中,服务存在不止一次或对于您的一月表存在相同。

    但这是一个非常规的设计。您描述的数据是经典的多对多,可以更好地设计如下:

    表 1:服务

    ServiceId
    +-----------+
    A
    B
    C
    D
    E
    

    表 2:月份

    | MonthId  | MonthName
    +----------+-----------+
    | 1        | Jan
    | 2        | Feb
    

    表 3:服务月数

    | ServiceId    | MonthId    | TotalNumber
    +--------------+------------+-------------+
    | A            | 2          | 8
    | A            | 1          | 5
    | B            | 1          | 15
    | D            | 2          | 32
    | E            | 2          | 36
    | E            | 1          | 25
    

    使用这样的关系和键:

    这可以作为 CrossTab 查询:

    TRANSFORM Sum(TotalNumber) AS SumOfTotalNumber
    SELECT ServiceId
    FROM ServiceMonths
    GROUP BY ServiceId
    PIVOT MonthId;
    

    结果如下:

    | ServiceId    | 1     | 2
    +--------------+-------+-----+
    | A            | 5     | 8
    | B            | 15    | 
    | D            |       | 32
    | E            | 25    | 36
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 2021-01-11
      相关资源
      最近更新 更多