我正在学习 SQL(初学者),其中一个概念是 CASES,这让我有点不知所措。我有这个数据库: [![在此处输入图片描述][1]][1]
pokedex_num | 精灵宝可梦名字 | 进化线 | evolution_line_number |
---|---|---|---|
1 | 灯泡龙 | 灯泡龙 | 1 |
2 | 常春藤龙 | 灯泡龙 | 2 |
3 | 金星 | 灯泡龙 | 3 |
1 | 松鼠 | 松鼠 | 1 |
2 | 疣龟 | 松鼠 | 2 |
3 | 水龟 | 松鼠 | 3 |
我必须把它转换成这张表:
第一次革命 | 二次进化 | 第三次进化 |
---|---|---|
灯泡龙 | 常春藤龙 | 金星 |
松鼠 | 疣龟 | 水龟 |
花了我一段时间,但我设法通过将 MAX 添加到我的 CASE 语句来避免 NULLS 来做到这一点。但是,当我现在尝试添加一个 ORDER BY pokedex_num,NULLS 返回时,我遇到了问题。
希望解释为什么会这样?
这是我目前的尝试:
SELECT MAX(CASE WHEN evolution_line_number = 1 THEN pokemon_name END) AS baseform
, MAX(CASE WHEN evolution_line_number = 2 THEN pokemon_name END) AS secondevolution
, MAX(CASE WHEN evolution_line_number = 3 THEN pokemon_name END) as thirdevolution
FROM training.pokemon
GROUP BY evolution_line, pokedex_num
ORDER BY pokedex_num
第一次革命 | 二次进化 | 第三次进化 |
---|---|---|
灯泡龙 | 空 | 空 |
空 | 常春藤龙 | 空 |
空 | 空 | 金星 |
松鼠 | 空 | 空 |
空 | 疣龟 | 空 |
空 | 空 | 水龟 |
您当前的查询返回
NULL
不是因为order by
,而是因为GROUP BY evolution_line, pokedex_num
,并且pokedex nums是不同的神奇宝贝。
我会考虑使用两个自连接,以防您想使用初始表的列,而不是名称。
例如:
select t1.pokedex_num, t1.pokemon_name l1, t2.pokemon_name l2, t3.pokemon_name l3 from ta t1
left join ta t2 on t2.evolution_line = t1.evolution_line and t2.evolution_line_number = 2
left join ta t3 on t3.evolution_line = t1.evolution_line and t3.evolution_line_number = 3
where t1.evolution_line_number = 1
Order by t1.pokedex_num
Demo可以看到here.