如何解决以其他表格为条件的SQL
我对此很陌生,所以我希望这很清楚。如何从一个表中获取数据,基于另一个表中该月之前的1个月?有2个表的示例。使用SQL。
第一张表A:成员,每个月花费的金额。名称+月份的主键组合
+---------+--------+--------+
| Name | Month | Amount |
+---------+--------+--------+
| James | 202001 | 10 |
| James | 202002 | 5 |
| James | 202003 | 8 |
| Michael | 202001 | 3 |
| Michael | 202002 | 4 |
| Michael | 202003 | 5 |
| Michael | 202004 | 6 |
| Tom.... | 202001 | 12 |
| Tom.... | 202002 | 10 |
| Tom.....| 202003 | 7 |
| Tom.... | 202004 | 2 |
+---------+--------+--------+
第二张表B:会员和月份未订阅。主键是名称。
+--------+--------+
| Name | Month |
+--------+--------+
| James | 202003 |
| Tom....| 202004 |
+--------+--------+
最终输出表:退订前1个月的会员人数和金额+当前会员的最新月份金额及其状态。主键应为名称。
+---------+--------+--------+--------------+
| Name | Month | Amount | Status |
+---------+--------+--------+--------------+
| James | 202002 | 5 | Unsubscribed |
| Tom | 202003 | 7 | Unsubscribed |
| Michael | 202004 | 6 | Subscribed |
+---------+--------+--------+--------------+
解决方法
这有点棘手。我认为这可以解决问题:
select t1.*,t2.amount,(case when t2.name is null then 'subscribed' else 'unsubscribed' end)
from (select t1.*,row_number() over (partition by name order b amount desc) as seqnum
from table1 t1
) t1 left join
table2 t2
on t1.name = t2.name
where t2.name is not null and seqnum = 2 or
t2.name is null and seqnum = 1;
,
CTE方法,
with unsubscribed as(select
first.name,first.month,first.amount
from table1 first
inner join table2 second
on lower(trim(first.name)) = lower(trim(second.name))
and first.month = second.month),subscribed as (select *,case when name not in (select distinct name from unsubscribed) then 'subscribed'
else 'unsubscribed' end as status from table1)
select name,month,amount,status from (
select *,row_number()over(partition by name order by month desc)as rn from subscribed
where (name,month) not in (select distinct name,month from unsubscribed)) where rn = 1
order by month
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。