我下面有两张桌子:
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
的所有日期,capacity
与qty
的总和{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