我有一个名为associate_ratings的表,其结构如下:
id int(11) NO PRI auto_increment
associate varchar(10) NO
skill_id int(11) NO MUL
rating int(11) NO
updated_time datetime NO
此表格包含该员工的技能(skill_id
)及其相应的rating
。
评级栏可以取值(1,2,3)
我想获得每项技能中有多少员工获得特定评级,请在下面输出表结构中找到:
Skill_id Rating1_count Rating2_count Rating3_count
Java 2 1 4
C# 3 2 2
这在Java中表示有2个评级为1,1的同事评级为2& 4名员工评级为3
我尝试了以下查询,但输出的格式不符合我的预期:
SELECT skill_id, rating, count(*) FROM associate_ratings a
WHERE updated_time = (
SELECT max(updated_time)
FROM skill_set.associate_ratings b
WHERE a.associate = b.associate
) GROUP BY a.skill_id, a.rating order by a.skill_id, a.rating;
您能告诉我如何以我想要的格式获取输出吗?
答案 0 :(得分:2)
使用临时表和案例
SELECT skill_id, sum(rating_1), sum(rating_2), sum(rating_3)
FROM (
SELECT a.skill_id as skill_id,
case a.rating when '1' then 1 else 0 end as rating_1,
case a.rating when '2' then 1 else 0 end as rating_2,
case a.rating when '3' then 1 else 0 end as rating_3
FROM associate_ratings a
WHERE updated_time = (
SELECT max(updated_time)
FROM skill_set.associate_ratings b
WHERE a.associate = b.associate
) ) as t
GROUP BY skill_id
ORDER BY skill_id;
答案 1 :(得分:0)
select Skill_id ,
count(case when rating = 1 then 1 else null end) as Rating1_count ,
count(case when rating = 2 then 1 else null end) as Rating2_count ,
count(case when rating = 3 then 1 else null end) as Rating3_count
from associate_ratings b
left join associate_ratings a
on b.Skill_id = a.Skill_id
group by Skill_id
答案 2 :(得分:0)
这将是这样的:
SELECT
skill_id,
sum(IF(rating=1,1,0)) as Rating1_count,
sum(IF(rating=2,1,0)) as Rating2_count,
sum(IF(rating=3,1,0)) as Rating3_count
FROM associate_ratings
GROUP BY skill_id
ORDER BY skill_id;
我认为这是最简单的解决方案。