以其他表格为条件的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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...