如何编写 SQL 查询以根据不同表中的值计算百分比?
How to write a SQL query to calculate percentages based on values across different tables?
假设我有一个包含两个表的数据库,类似于以下内容:
Table 1:
tweet_id tweet
1 Scrap the election results
2 The election was great!
3 Great stuff
Table 2:
politician tweet_id
TRUE 1
FALSE 2
FALSE 3
我正在尝试编写一个 SQL 查询,其中 return 包含单词 'election'
的推文的百分比按他们是否是政客细分。
例如,Table 1
中的前 2 条推文包含单词 election
。通过查看Table 2
,可以看到tweet_id
1是由politician
写的,而tweet_id
2是由non-politician
写的。
因此,SQL 查询的结果应该 return 50% 用于政客,50% 用于非政客(即两条推文包含单词 'election',一条由一条政治家和一个非政治家)。
知道如何在 SQL 中写这个吗?
您可以像这样使用聚合:
select t2.politician, avg( case when t.tweet like '%election%' then 1.0 else 0 end) as election_ratio
from tweets t join
table2 t2
on t.tweet_id = t2.tweet_id
group by t2.politician;
Here 是一个 db<>fiddle.
您可以通过为 return 所有选举推文创建一个子查询,并为 return 所有政客的选举推文创建一个子查询,然后加入。
这是一个示例。请注意,您可能需要在除法之前将总数转换为小数(取决于您使用的 SQL 供应商)。
select
politician_tweets.total / election_tweets.total
from
(
select
count(tweet) as total
from
table_1
join table_2 on table_1.tweet_id = table_2.tweet_id
where
tweet like '%election%'
) election_tweets
join
(
select
count(tweet) as total
from
table_1
join table_2 on table_1.tweet_id = table_2.tweet_id
where
tweet like '%election%' and
politician = 1
) politician_tweets
on 1 = 1
假设我有一个包含两个表的数据库,类似于以下内容:
Table 1:
tweet_id tweet
1 Scrap the election results
2 The election was great!
3 Great stuff
Table 2:
politician tweet_id
TRUE 1
FALSE 2
FALSE 3
我正在尝试编写一个 SQL 查询,其中 return 包含单词 'election'
的推文的百分比按他们是否是政客细分。
例如,Table 1
中的前 2 条推文包含单词 election
。通过查看Table 2
,可以看到tweet_id
1是由politician
写的,而tweet_id
2是由non-politician
写的。
因此,SQL 查询的结果应该 return 50% 用于政客,50% 用于非政客(即两条推文包含单词 'election',一条由一条政治家和一个非政治家)。
知道如何在 SQL 中写这个吗?
您可以像这样使用聚合:
select t2.politician, avg( case when t.tweet like '%election%' then 1.0 else 0 end) as election_ratio
from tweets t join
table2 t2
on t.tweet_id = t2.tweet_id
group by t2.politician;
Here 是一个 db<>fiddle.
您可以通过为 return 所有选举推文创建一个子查询,并为 return 所有政客的选举推文创建一个子查询,然后加入。
这是一个示例。请注意,您可能需要在除法之前将总数转换为小数(取决于您使用的 SQL 供应商)。
select
politician_tweets.total / election_tweets.total
from
(
select
count(tweet) as total
from
table_1
join table_2 on table_1.tweet_id = table_2.tweet_id
where
tweet like '%election%'
) election_tweets
join
(
select
count(tweet) as total
from
table_1
join table_2 on table_1.tweet_id = table_2.tweet_id
where
tweet like '%election%' and
politician = 1
) politician_tweets
on 1 = 1