我有一个包含下面提到的字段和结构的数据库:
id BIGINT UNSIGNED PRIMARY KEY
name VARCHAR(255) #Game ID
platform VARCHAR(255) #The name of the game
year_of_release YEAR #Year of publication
genre VARCHAR(255) #Game genre
publisher VARCHAR(255) #Producer
na_sales DOUBLE(10,2) #Sales volume in North America
other_sales DOUBLE(10,2) #Sales volume in Asia, Europe, and Australia
global_sales DOUBLE(10,2) #Amount of sales in the world
由于该项目的复杂性,并且该表的测试输入位于下面的 SQL 脚本文件中:
https://uploadb.me/knde5s545g6i/games.sql.html
您可以通过以下文件创建带有就绪信息的游戏桌
我的问题:
我想使用 case 语句编写一个查询 产量中显示名称、出版年份、亚洲、欧洲、澳洲销量及全球销量;首先,发表年份为2000年以后的结果中出现行。出版年份在2000年以后的系列应按全球销量降序排列,出版年份在2000年之前的系列应按亚洲、欧洲和澳大利亚销量降序排列。最后如果有全球销量相同或者亚洲、欧洲、澳洲销量相同的行,则按游戏ID升序排序。
我的代码:
select name, year_of_release, other_sales, global_sales from games
where case
when year_of_release >= 2000 then year_of_release
else year_of_release
end order by case
when year_of_release >= 2000 then global_sales
when year_of_release < 2000 then other_sales
end desc;
但是我的输出不正确,正如我在问题中提到的:
与我的问题不同,输出的是其中year_of_release字段大于2000的记录
您应该首先按分隔两组结果的条件进行排序。然后在每个组中,您按适当的销售额进行订购。
SELECT name, year_of_release,
CASE WHEN year_of_release >= 2000 THEN global_sales
ELSE other_sales
END AS sales
FROM games
ORDER BY year_of_release < 2000 ASC,
CASE WHEN year_of_release >= 2000 THEN global_sales
ELSE other_sales
END DESC,
id ASC
条件的值为 true 时为
1
或 false 时为 0
,您可以以此排序。
您对问题的描述似乎不正确,因为
ORDER BY
不会删除结果。所以它应该会返回所有年份,只是不按照您预期的顺序。