MS Access在连接的表上输出重复的行

时间:2015-07-16 03:46:52

标签: sql ms-access

我一直把头发拉出来。

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

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

问题是,我希望在输出中获取disticnt行来对应服务类型列表,但是我为服务类型获取了多行,每个月都有交替计数。

我错过了什么吗?

这是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;

1 个答案:

答案 0 :(得分: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;

我认为这意味着您在其中一个表中有重复值。换句话说,在你的Feb表中,一个服务对于你的Jan表存在多次或相同。

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

表1:服务

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

表2:月份

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

表3:ServiceMonths

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

使用这样的关系和键:

enter image description here

这可以作为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