需要显示特定用户在该目标月份完成了多少billing_amount?我有两个表,一个是目标表,另一个是closure_emp。
SELECT fk_user_id,target_month,target
FROM `target`
WHERE fk_user_id='31' and target_month > DATE_SUB(now(), INTERVAL 6 MONTH)
这显示了6条记录
fk_user_id target_month target
31 2013-08-01 100000
31 2013-09-01 100000
31 2013-10-01 120000
31 2013-11-01 120000
31 2013-12-01 120000
和
SELECT *
FROM `closure_employee`
WHERE ce_recruiter_id='31' and offer_date > DATE_SUB(now(), INTERVAL 7 MONTH)
显示2条记录
user_id billing_amount offer_date joining_date
31 390000 2013-08-30 2-09-2013
31 208354 2013-09-30 25-11-2013
我需要查询以将两个表都显示在一个表中,如下所示
fk_user_id target_month target user_id billing_amount
31 2013-08-01 100000 31 390000
31 2013-09-01 100000 31 208354
31 2013-10-01 120000 31 null
31 2013-11-01 120000 31 null
31 2013-12-01 120000 31 null
请帮我。
看来您可以通过LEFT JOIN
在表之间使用a来获得结果。由于您要返回target
表中的所有行,因此您将LEFT JOIN
在closure_employee
上找到该表user_id
。
为了正确分配billing_amount
从每一行target
,你就需要使用month()
值的target_month
和offer_date
-这也将是你的连接条件的一部分。
该查询将类似于以下内容:
select t.fk_user_id,
t.target_month,
t.target,
e.user_id,
e.billing_amount
from target t
left join closure_employee e
on t.fk_user_id = e.user_id
and month(t.target_month) = month(e.offer_date)
and e.offer_date > DATE_SUB(now(), INTERVAL 7 MONTH)
where t.target_month > DATE_SUB(now(), INTERVAL 6 MONTH);
请参阅带有演示的SQL Fiddle。您会注意到,offer_date
返回前7个月的过滤器已添加到联接条件中,而不是where子句中-这样做仍将返回该closure_employee
时间范围内的行,但也会返回target
表中的所有行这似乎是您想要的行为。
如果您需要通过ce_recruiter_id
和添加过滤器,fk_user_id
则可以将上述查询更改为:
select t.fk_user_id,
t.target_month,
t.target,
e.user_id,
e.billing_amount
from target t
left join closure_employee e
on t.fk_user_id = e.user_id
and month(t.target_month) = month(e.offer_date)
and e.offer_date > DATE_SUB(now(), INTERVAL 7 MONTH)
and e.ce_recruiter_id='31'
where t.target_month > DATE_SUB(now(), INTERVAL 6 MONTH)
and t.fk_user_id='31'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句