【问题标题】:Creating a new column based on a condition from 2 different tables in SQL根据 SQL 中 2 个不同表的条件创建新列
【发布时间】:2020-10-26 14:00:54
【问题描述】:
我有 2 个表,我正在形成一个查询来提取数据,其中包含一个显示客户类型的新列(免费/高级)
我附上了一张图片,其中一张桌子上有关于姓名的信息,而另一张桌子上有付款信息。
我想要以第三列 TYPE 的形式显示的结果,并且根据表 B 中的付款信息,它应该显示 Premium else Null。
我正在尝试使用 CASE & JOIN 但我无法制定查询。请帮忙
【问题讨论】:
标签:
sql
subquery
case
inner-join
【解决方案1】:
我了解,至少支付了一笔款项的客户是“Premium”,而其他客户是“Free”。如果是这样,您可以使用exists 和case 表达式:
select a.*
case when exists (select 1 from tableb b where b.userid = a.userid)
then 'Premium'
else 'Free'
end as type
from tablea a
【解决方案2】:
嗯。 . .我认为您希望type 基于b 中匹配行的存在:
select a.*,
(case when exists (select 1 from b where b.user_id = a.user_id)
then 'Premium' else 'Free'
end) as type
from a;