我刚刚开始学习SQL(特别是SQLite),并且一直在使用this数据。
此列表中的每个Marvel角色都有每个属性的等级(强度,智力,速度等),我想找出每个属性有多少个角色具有最大的作用。例如,有多少个角色以力量为最大属性?
我们可以假设,如果一个角色具有两个或多个最高属性,该角色将计入每个属性。
我期望的输出是这样的:
best_Attribute COUNT(*)
__________________________________
intelligence a
strength b
speed c
durability d
energy_Projection e
fighting_Skills f
这是我的尝试:
SELECT COUNT(*),
CASE
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == intelligence THEN "intelligence"
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == strength THEN "strength"
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == speed THEN "speed"
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == durability THEN "durability"
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == energy_Projection THEN "energy_Projection"
WHEN MAX(intelligence, strength, speed, durability, energy_Projection, fighting_Skills) == fighting_Skills THEN "fighting_Skills"
END as "best_Attribute"
FROM marvels
GROUP BY best_Attribute;
这很丑陋,冗长,甚至无法正常工作。输出如下:
COUNT(*) best_Attribute
__________________________
2 4
3 6
7 7
是否有(不错的)方法来获得所需的输出?
答案 0 :(得分:2)
我不确定您是否需要确切的建议输出。我可以提供以下查询,该查询会将整个表中的属性计数报告为单独的列。
SELECT
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = intelligence THEN 1 END) AS intelligence_count
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = strength THEN 1 END) AS strength_count
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = speed THEN 1 END) AS speed_count
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = durability THEN 1 END) AS durability_count
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = energy_Projection THEN 1 END) AS energy_Projection_count
COUNT(CASE WHEN MAX(intelligence, strength, speed, durability, energy_Projection,
fighting_Skills) = fighting_Skills THEN 1 END) AS fighting_Skills_count
FROM marvels;
请注意,如果要对整个表格进行总计,则无需在此处使用GROUP BY
。
答案 1 :(得分:1)
Tim的解决方案是性能最高的方法-以及您如何解决该问题。但是,另一种方法是取消数据透视并使用聚合。我只想提供此方法作为替代方案,以便您可以看到在SQL中解决问题的不同方法:
with a as (
select name, 'intelligence' as attribute, intelligence as val
from marvels
union all
select name, 'strength' as attribute, strength as val
from marvels
union all
select name, 'speed' as attribute, speed as val
from marvels
union all
select name, 'durability' as attribute, durability as val
from marvels
union all
select name, 'energy_Projection' as attribute, energy_Projection as val
from marvels
union all
select name, 'fighting_Skills' as attribute, fighting_Skills as val
from marvels
)
select a.attribute, count(*) as num_with_max
from a
where a.val = (select max(a2.val) from a a2 where a2.name = a.name)
group by a.attribute;