我是否需要一个日历来连接访问表并按月报告

时间:2016-11-07 16:33:34

标签: sql ms-access inner-join outer-join

我需要在Access中加入3个表。所以我创建了查询以获得" Team"具有内连接的字段[表A]到[表C] on" Assoc。 NO"然后另一个[表B]到[表C]也在" Assoc。 NO]。

我的问题

我使用基于[表C]和[表A]的查询来获得月份,但是如果它们在[表A]中不存在并且仅存在[表B]则我错过了几个月。我是否需要创建一个只有几个月和几年的表并创建一个连接?我为长篇文章道歉,但希望提供尽可能多的信息。在此先感谢您的帮助。

Table A
|Name         | Assoc. NO |month|Year|Product|SaleA|
|John Smith   |   1       |Jan  |2016|Apple  |$10 |
|John Smith   |   1       |Jan  |2016|Pear   |$5  |
|John Smith   |   1       |Feb  |2016|Apple  |$10 |
|George Martin|   2       |Feb  |2016|Apple  |$10 |
|George Martin|   2       |Feb  |2016|Apple  |$10 |
|George Martin|   2       |Feb  |2016|Pear   |$5  |


Table B
|Name         | Assoc. NO |month|Year|Service   |SaleB|
|John Smith   |   1       |Jan  |2016|oil change|$25  |
|George Martin|   2       |Jan  |2016|oil change|$25  |
|Mark James   |   3       |Feb  |2016|oil change|$25  |
|Mark James   |   3       |Mar  |2016|oil change|$25  |
|George Martin|   2       |Mar  |2016|oil change|$25  |

Table C
|Team   |Name         | Assoc. NO |
|Team A |John Smith   |   1       |
|Team B |George Martin|   2       |
|Team B |Mark James   |   3       |

我希望看到以下内容:

Query 
|Team   |Name         | Month  |Sale |SaleB|SUM(SaleA,SaleB)|
|-------|-------------|--------|-----|-----|----------------|
|Team A |John Smith   |   Jan  | $15 | $25 |  $40           |
|Team A |John Smith   |   Feb  | $10 | $0  |  $10           |
|Team B |George Martin|   Jan  | $0  | $25 |  $25           |
|Team B |George Martin|   Feb  | $25 | $0  |  $25           |
|Team B |George Martin|   Mar  | $0  | $25 |  $25           |
|Team C |Mark James   |   Feb  | $0  | $25 |  $25           |
|Team C |Mark James   |   Feb  | $0  | $25 |  $25           |

1 个答案:

答案 0 :(得分:0)

SELECT [Table C].Team, [Table C].Name, [Table C].[Assoc No], Month, Sum(T.SaleA) AS TotA, Sum(T.SaleB) AS TotB, [TotA]+[TotB] AS Total
FROM

(select [Assoc no], Month, SaleA, 0 as SaleB from [Table A] 
UNION ALL select [Assoc No], Month, 0, Saleb from [Table B])  AS T

INNER JOIN [Table C] ON T.[Assoc No]= [Table C].[Assoc No]
GROUP BY [Table C].Team, [Table C].Name, Table C].[Assoc No], T.Month;