-1

我有两个表,如下所示.. 我需要在 sql 查询中使用 join 连接两个表,但我是新手,所以请帮助我.. 因为我需要输出表,如第三个表所示

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_金额:

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
4

3 回答 3

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


另请注意,您的MonthIDmonth_id字段名称不一致。

于 2013-08-29T06:21:00.623 回答
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 

演示

于 2013-08-29T06:32:00.230 回答
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]);
于 2014-04-06T03:39:04.817 回答