我有2张桌子。表1和表2.
表1数据:
Id org_id start_date end_date month
'1', '46', '2015-01-01', '2015-01-31', 'January'
'2', '46', '2015-02-01', '2015-02-28', 'February'
'3', '46', '2015-03-01', '2015-03-31', 'March'
'4', '46', '2015-04-01', '2015-04-30', 'April'
'5', '46', '2015-05-01', '2015-05-31', 'May'
'6', '46', '2015-06-01', '2015-06-30', 'June'
'7', '46', '2015-07-01', '2015-07-31', 'July'
'8', '46', '2015-08-01', '2015-08-31', 'August'
'9', '46', '2015-09-01', '2015-09-30', 'September'
'10', '46', '2015-10-01', '2015-10-31', 'October'
'11', '46', '2015-11-01', '2015-11-30', 'November'
'12', '46', '2015-12-01', '2015-12-31', 'December'
表2数据:
Id org_id from_date emp_id
'48', '46', '2015-06-09' 1
'49', '46', '2015-06-09' 1
'50', '46', '2015-06-01' 2
'51', '46', '2015-05-20' 1
'56', '46', '2015-07-07' 2
这是我的疑问:
select t1.month,count(t2.emp_id) as count
from Table1 t1
left outer join Table2 t2 on t2.from_date between t1.start_date and t1.end_date
where t2.org_id=46 group by t1.month
我得到的输出是:
month count
'July', '1'
'June', '3'
'May', '1'
我期待的输出是:
month count
'January', '0'
'February', '0'
'March', '0'
'April', '0'
'May', '1'
'June', '3'
'July', '1'
'August', '0'
'September', '0'
'October', '0'
'November', '0'
'December', '0'
我使用左外连接。但左表中的所有记录都没有获取。
任何帮助!!
答案 0 :(得分:3)
您必须将where
身份的部分放入on clase:
select t1.month,count(t2.emp_id) as count
from Table1 t1
left outer join Table2 t2 on t2.from_date between t1.start_date and t1.end_date
and t2.org_id=46 group by t1.month
如果您不这样做,则会有inner join
答案 1 :(得分:1)
试试这个..
SELECT t1.month,COUNT(t2.emp_id) AS COUNT
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.from_date BETWEEN t1.start_date AND t1.end_date
AND t2.org_id=46 GROUP BY t1.month