在左外连接中使用Sum函数

时间:2016-02-02 19:57:33

标签: sql ms-access left-join

我下面有两张桌子:

1. DatesMaster

+----------+---------------+
|  m_date  |    capacity   |
+----------+---------------+
| 1/2/2016 |          10   |
| 2/2/2016 |          10   |
| 3/2/2016 |          10   |
+----------+---------------+

2. Schedule

+----------+-------+
| sch_date | qty   |
+----------+-------+
| 1/2/2016 |   2   |
| 1/2/2016 |   2   |
| 1/2/2016 |   2   |
| 2/2/2016 |   5   |
| 2/2/2016 |   5   |
| 3/2/2016 |   5   |
| 3/2/2016 |   1   |
+----------+-------+

如何使用左外连接获得capacity - qty的结果,我可以DatesMaster显示Availability的所有日期,capacityqty的总和{1}}相同日期?

1 个答案:

答案 0 :(得分:0)

SELECT中不属于GROUP BY的任何列都必须包含在聚合函数中,以便您可以在此查询中使用MAX

SELECT DatesMaster.m_date
    ,MAX(DatesMaster.capacity) - SUM(Schedule.qty) AS Balance
FROM DatesMaster
LEFT JOIN Schedule ON DatesMaster.m_date = Schedule.sch_date
GROUP BY DatesMaster.m_date

或者,将capacity列添加到GROUP BY

SELECT DatesMaster.m_date
    ,(DatesMaster.capacity) - SUM(Schedule.qty) AS Balance
FROM DatesMaster
LEFT JOIN Schedule ON DatesMaster.m_date = Schedule.sch_date
GROUP BY DatesMaster.m_date, DatesMaster.capacity