在访问查询中加入三个具有列总和的表

时间:2013-08-29 07:58:30

标签: sql ms-access

我有三个表,如下所示.. 我需要输出如输出表所示 为此,我需要按月顺序加入三个表和订单输出

tbl_MonthList

MonthID   MonthList
1         January
2         February
3         March
4         April
5         May
6         June
7         July
8         August
9         September
10        October
11        November
12        December

tbl_Amount:

Month_id     Amount_Received     Customer_id
3             500                 aaa
3            1000                 bbb
4             700                 jjj
5             300                 aaa
5             400                 jjj
5             500                 ppp
7            1000                 aaa
10           1500                 bbb
12            700                 jjj

tbl_Month_Target

MonthID     MonthF_L
1             10000
2            150000
3              1000
4             50000
5              5000
6              3000
7             20000
8             12000
9             34000
10            85000
11            34000
12            45000

我需要输出如下所示

Month     Total_amount     MonthF_L
January           0          10000
February          0         150000
March          2000           1000
April           700          50000
May            1200           5000
June              0           3000
July           1000          20000
August            0          12000
September         0          34000
October        1500          85000
November          0          34000
December        700          45000

2 个答案:

答案 0 :(得分:3)

SELECT ML.MonthList AS Month, 
       Sum(A.Amount_Received) AS Total_amount, 
       First(MT.MonthF_L) AS MonthF_L
FROM (tbl_MonthList AS ML 
      INNER JOIN tbl_Month_Target AS MT ON ML.MonthID = MT.MonthID) 
      LEFT JOIN tbl_Amount AS A ON ML.MonthID = A.Month_id
GROUP BY ML.MonthList, ML.MonthID
ORDER BY ML.MonthID

注意:在MS Access中,multiple joins must be explicitly nested within parentheses

答案 1 :(得分:0)

试试这个:

select ml.MonthList, sum(a.Amount_Received), mt.MonthF_L from tbl_MonthList ml
left join tbl_Month_Target mt on mt.MonthID = ml.MonthID
left join tbl_Amount a on ml.Month_id = ml.MonthID 
group by ml.MonthList, mt.MonthF_L