以下sql工作正常并按预期返回90条记录,并且计数也正确但是在sql中添加日期过滤时,它只返回44行而不是90行,但总计数是正确的。
没有日期过滤的SQL:
sql without date filtering:
SELECT
t4.firstname,
t1.category
,COUNT(t3.catid) as days
FROM category AS t1
LEFT JOIN (SELECT
DISTINCT empid,t1.catid
FROM attendance AS t2
LEFT JOIN category AS t1 ON (t1.catid>0)
) AS t2
ON (t1.catid=t2.catid)
LEFT JOIN attendance AS t3 ON (t2.empid=t3.empid AND t3.catid=t2.catid)
left join employee t4 on t2.empId=t4.empid
GROUP BY t2.empid,t2.catid
ORDER BY t2.empid,t2.catid;
日期过滤:
SELECT
t4.firstname,
t1.category
,COUNT(t3.catid) as days
FROM category AS t1
LEFT JOIN (SELECT
DISTINCT empid,t1.catid
FROM attendance AS t2
LEFT JOIN category AS t1 ON (t1.catid>0)
) AS t2
ON (t1.catid=t2.catid)
LEFT JOIN attendance AS t3 ON (t2.empid=t3.empid AND t3.catid=t2.catid)
left join employee t4 on t2.empId=t4.empid
where
date_format(dateIn, '%Y-%m-%d')>=str_to_date("1/01/2015", '%m/%d/%Y')
and date_format(dateout, '%Y-%m-%d')<=str_to_date("12/31/2015", '%m/%d/%Y')
GROUP BY t2.empid,t2.catid
ORDER BY t2.empid,t2.catid;
答案 0 :(得分:0)
使用date_format
时,你正在比较字符串,所以一切都搞砸了。我建议您使用between
而不是像date_field BETWEEN '2015-01-01' AND '2015-12-31'
这样的两个条件,并坚持使用YYYY-MM-DD格式。
SELECT
t4.firstname,
t1.category
,COUNT(t3.catid) as days
FROM category AS t1
LEFT JOIN (SELECT
DISTINCT empid,t1.catid
FROM attendance AS t2
LEFT JOIN category AS t1 ON (t1.catid>0)
) AS t2
ON (t1.catid=t2.catid)
LEFT JOIN attendance AS t3 ON (t2.empid=t3.empid AND t3.catid=t2.catid)
left join employee t4 on t2.empId=t4.empid
where
dateIn between '2015-01-01' and '2015-12-31'
GROUP BY t2.empid,t2.catid
ORDER BY t2.empid,t2.catid;