我正在尝试获取具有以下详细信息的销售人员列表 EmpId,推销员连续三年获得A级。
我编写了以下查询,但出现错误。
SELECT salesman, empid
FROM Sales_temp
where rating = 'A'
AND(select max(year), min(year) from Sales_temp
having (max(year)-min(year) = 3))
AND Count(year)=3
要过滤连续3年获得“ A”级数据,我使用了以下逻辑:
A等级的最大值(年)与A等级的最小值(年)之差= 3 计数(年)= 3。但是,出现错误:
标量子查询不能超过一列
请提出建议。
答案 0 :(得分:2)
我想在MySQL中做到这一点的唯一方法是将您的表自我连接两次,然后由业务员进行汇总。然后,确定推销员是否至少有一项记录具有连续三个A级:
SELECT
s1.salesman, s1.empid
FROM Sales_temp s1
INNER JOIN Sales_temp s2
ON s1.empid = s2.empid AND s2.year = s1.year + 1
INNER JOIN Sales_temp s3
ON s2.empid = s3.empid AND s3.year = s2.year + 1
GROUP BY
s1.salesman, s1.empid
HAVING
SUM(CASE WHEN s1.rating = 'A' AND s2.rating = 'A' AND s3.rating = 'A'
THEN 1 ELSE 0 END) > 0;
中间连接表非常丑陋,但是足以说它给Sales_temp
中的每条记录一个与下一年,然后是下一年配对的机会。如果可以进行三连击,并且所有三个等级均为A
质量,则该推销员将出现在结果集中。
答案 1 :(得分:0)
If you are interested in the years A was achieved
drop table if exists sales_temp;
create table sales_temp(salesman int,empid int, rating varchar(1),year int);
insert into sales_temp values
(1,1,'a',2018),(1,1,'a',2017),(1,1,'a',2016),(1,1,'a',2015),
(2,2,'a',2018),(2,2,'a',2017),
(3,3,'b',2018),(3,3,'a',2017),(3,3,'a',2016),(3,3,'a',2015);
select salesman,empid,r1,r2,r3
from
(
select s.salesman,s.empid,year r1,
(select year from sales_temp s1 where s1.salesman = s.salesman and s1.empid = s.empid and s1.year = s.year -1 and rating = 'a') r2,
(select year from sales_temp s1 where s1.salesman = s.salesman and s1.empid = s.empid and s1.year = s.year -2 and rating = 'a') r3
from sales_temp s
where s.rating = 'a'
) s
where s.r1 is not null and s.r2 is not null and s.r3 is not null ;
+----------+-------+------+------+------+
| salesman | empid | r1 | r2 | r3 |
+----------+-------+------+------+------+
| 1 | 1 | 2018 | 2017 | 2016 |
| 1 | 1 | 2017 | 2016 | 2015 |
| 3 | 3 | 2017 | 2016 | 2015 |
+----------+-------+------+------+------+
3 rows in set (0.00 sec)