我有两个表,如下所示.. 我需要使用连接在SQL查询中加入两个表,但我是新的,所以请帮助我.. 因为我需要输出表,如第三表所示
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
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
Month Total_amount
January 0
February 0
March 2000
April 700
May 1200
June 0
July 1000
August 0
September 0
October 1500
November 0
December 700
答案 0 :(得分:1)
SELECT
tbl_MonthList.MonthList AS Month,
COALESCE(SUM(tbl_Amount.Amount_Received), 0) AS Total_amount
FROM
tbl_MonthList
LEFT JOIN
tbl_Amount
ON tbl_MonthList.MonthID = tbl_Amount.month_id
GROUP BY
tbl_MonthList.MonthList
即使LEFT JOIN
中没有匹配的行,tbl_MonthList
也会确保您仍然可以从tbl_Amount
获取每一行。
然后这是一个正常SUM()
,GROUP BY
。
由于没有数据的SUM()
(例如您的示例中的第1个月)是NULL
,我们使用COALESCE()
来转换NULL
进入0
。
另请注意,您的MonthID
和month_id
字段名称不一致。
答案 1 :(得分:0)
SELECT t1.month,SUM(t2.amount) as SUM FROM Table1 t1 LEFT JOIN Table2 t2 ON t1.monthid = t2.monthid GROUP BY t1.monthid
答案 2 :(得分:0)
SELECT Count(PINJAM.Tgl) AS Peminjam, DatePart("yyyy",[Tgl]) AS Tahun, DatePart("m",[Tgl]) AS Bulan, IIf(DatePart("m",[Tgl])=1,"Januari",IIf(DatePart("m",[Tgl])=2,"Februari",IIf(DatePart("m",[Tgl])=3,"Maret",IIf(DatePart("m",[Tgl])=4,"April",IIf(DatePart("m",[Tgl])=5,"Mei",IIf(DatePart("m",[Tgl])=6,"Juni",IIf(DatePart("m",[Tgl])=7,"Juli",IIf(DatePart("m",[Tgl])=8,"Agustus",IIf(DatePart("m",[Tgl])=9,"September",IIf(DatePart("m",[Tgl])=10,"Oktober",IIf(DatePart("m",[Tgl])=11,"November","Desember"))))))))))) AS Ket
FROM PINJAM
GROUP BY DatePart("yyyy",[Tgl]), DatePart("m",[Tgl]), Format([Tgl],"m/yyyy"), IIf(DatePart("m",[Tgl])>1,"Januari","Februari")
ORDER BY DatePart("yyyy",[Tgl]), DatePart("m",[Tgl]);