案例 when 语句在 oracle 中的跨表

1 sql oracle

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

我有两张桌子。我已经真诚地尝试遵循社区标准,但以防万一它不起作用,表 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;
Run Code Online (Sandbox Code Playgroud)

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

小智 5

也许试试 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;
Run Code Online (Sandbox Code Playgroud)

或枢轴

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'));
Run Code Online (Sandbox Code Playgroud)

  • 没有这样的规则!该问题被标记为 Oracle,因此使用 Oracle 语法的答案是合适的。 (2认同)