我需要找到符合其销售目标的人员的员工ID,并根据其销售目标为每个员工获得多少奖金。
create table ta(
empid int(10),
sales int(10)
);
empid - sales
101 - 9898
201 - 988
301 - 87988
401 - 88
501 - 202088
create table tb(
target int(10),
bonus varchar(100));
Target - Bonus
1000 - 25%
5000 - 50%
10000 - 70%
50000 - 85%
100000 - 100%
================================= 我已经尝试过
select ta.*
from ta
right outer join tb on ta.sales=tb.target
where sales <= bonus;
还有
select empid, sales, target, bonus
from ta
join tb on ta.empid=tb.bonus
where target < 100000
答案 0 :(得分:1)
首先获取员工已达到的所有目标,然后获取最高目标:
select t.empid, t.target, tb.bonus from (
select empid, max(target) target
from (
select *
from ta inner join tb
on tb.target <= ta.sales
) g
group by empid
) t inner join tb on tb.target = t.target
请参见demo。
结果:
| empid | target | bonus |
| ----- | ------ | ----- |
| 101 | 5000 | 50% |
| 301 | 50000 | 85% |
| 501 | 100000 | 100% |
答案 1 :(得分:0)
您可以使用GROUP BY
使用以下解决方案:
SELECT ta.empid, ta.sales, MAX(tb.target) AS target, CONCAT(MAX(REPLACE(tb.bonus, '%', '') + 0), '%') AS bonus
FROM ta LEFT JOIN tb ON tb.target <= ta.sales
GROUP BY ta.empid, ta.sales
ORDER BY ta.empid
要获得所有员工,可以使用LEFT JOIN
。如果您只想查看有奖金的员工,则必须使用INNER JOIN
或HAVING
上的条件,如下所示:
SELECT ta.empid, ta.sales, MAX(tb.target) AS target, CONCAT(MAX(REPLACE(tb.bonus, '%', '') + 0), '%') AS bonus
FROM ta LEFT JOIN tb ON tb.target <= ta.sales
GROUP BY ta.empid, ta.sales
HAVING MAX(tb.target) IS NOT NULL -- or just using INNER JOIN
ORDER BY ta.empid