首页 > 解决方案 > oracle中跨表的case when语句

问题描述

嗨,为格式化道歉,但我很难过和沮丧,我只需要一些帮助。

我有两张桌子。我真诚地尝试遵循社区标准,但以防万一它不起作用,表 A 有 3 列“ID”,用于识别销售代表,“开始”表示他们开始的公司术语,“销售”用于表明他们在第一学期的销售额。表 B 只是表 A 的扩展,其中列出了销售人员在场的所有条款(我将其标记为季度)及其销售额。

表 A

+----+---------+--------+
| 身份证 | 季度 | 销售 |
+----+---------+--------+
| 1 | 141 | 30 |
| 2 | 151 | 50 |
| 3 | 151 | 80 |
+----+---------+--------+

表 B

+----+---------+--------+
| 身份证 | 季度 | 销售 |
+----+---------+--------+
| 1 | 141 | 30 |
| 1 | 142 | 25 |
| 1 | 143 | 45 |
| 2 | 151 | 50 |
| 2 | 152 | 60 |
| 2 | 153 | 75 |
| 3 | 151 | 80 |
| 3 | 152 | 50 |
| 3 | 153 | 70 |
+----+---------+--------+

我想要的输出是一个表格,其中包含 ID、开始期限、该期限的销售额、第二期限、该期限的销售额等。对于员工所在的前 6 个期限

我的代码是这个

select a.id, start, a.sales,
case when a.start+1 = b.quarter then sales end as secondquartersales,
case when a.start+2 = b.quarter then sales end as thridquartersales,.....
from tablea a
left join tableb b
on a.id = b.id;

它为所有 case when 语句提供空值。请帮忙

标签: sqloracle

解决方案


也许试试 GROUP BY

create table a ( id number, strt number, sales number);
create table b (id number, quarter number , sales number);

insert into a values (1,141,30);
insert into a values (2,151,50);
insert into a values (3,151,80);

insert into b values ( 1,141,30);
insert into b values ( 1,142,25);
insert into b values ( 1,143,45);
insert into b values ( 2,151,50);
insert into b values ( 2,152,60);
insert into b values ( 2,153,75);
insert into b values ( 3,151,80);
insert into b values ( 3,152,50);
insert into b values ( 3,153,70);

 select a.id, a.strt, a.sales, 
    max(case when a.strt+1 = b.quarter then b.sales end ) as secondquartersales,
    max(case when a.strt+2 = b.quarter then b.sales end ) as thridquartersales
from  a, b
where  a.id = b.id
group by  a.id, a.strt, a.sales;

或枢轴

select * from (
select a.id, 
    case when a.strt+1 = b.quarter then 'Q2'  
        when a.strt+2 =  b.quarter then  'Q3'  
        when a.strt+3 =  b.quarter then  'Q4' 
        when a.strt = b.quarter then 'Q1'end  q,
        b.sales sales
    
from  a, b
where  a.id = b.id) 
pivot ( max(nvl(sales,0)) for Q in ('Q1', 'Q2', 'Q3', 'Q4'));

推荐阅读