我已经创建了两个表,现在我想要找到每个平台(Hulu, Disney和Netflix)产生最高收入的电影。这里的问题是我不知道如何输出平台的名称,因为它是一个列标题。有人能帮我吗?
CREATE TABLE "StreamedMovies" (
"Title" TEXT,
"Netflix" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise
"Hulu" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise
"Disney" INTEGER, -- 1 if the movie is streamed in this platform, 0 otherwise
"ScreenTime" REAL,
PRIMARY KEY("Title")
)
CREATE TABLE "MovieData" (
"Title" TEXT,
"Genre" TEXT,
"Director" TEXT,
"Casting" TEXT,
"Rating" REAL,
"Revenue" REAL,
PRIMARY KEY("Title")
)
你必须写一个case语句。
select
Title,
case
when Netflix == 1 then 'Netflix'
when Hulu = 1 then 'Hulu'
when Disney = 1 then 'Disney'
end as Platform
from StreamedMovies
这表明你的设计有缺陷。有一些缺陷。例如,没有什么可以阻止一行拥有多个平台。或者没有平台。或者将平台设置为42。
相反,添加一个平台表和一个连接表来指示哪些电影在哪些平台上播放。
我们会解决一些其他的问题。
- 标题可以更改。使用一个简单的整数为主键。
- 不要引用列名和表名,这会使它们区分大小写。
- 声明外键。
- 使用not null来要求重要的数据
-- The platforms available for streaming.
create table platforms (
id integer primary key,
name text not null
);
insert into platforms (id, name)
values ('Netflix'), ('Hulu'), ('Disney+');
-- The movies.
create table movies (
id integer primary key,
title text not null
);
insert into movies (title) values ('Bad Taste');
-- A join table for which platforms movies are streaming on.
create table streamed_movies (
movie_id integer not null references movies,
platform_id integer not null references platforms
);
insert into streamed_movies (movie_id, platform_id) values (1, 1), (1, 3);
select
movies.title, platforms.name
from streamed_movies sm
join movies on sm.movie_id = movies.id
join platforms on sm.platform_id = platforms.id
title name
--------- -------
Bad Taste Netflix
Bad Taste Disney+