sql - 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 语句提供空值。请帮忙
解决方案
也许试试 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'));
推荐阅读
- php - 在 PHP 中合并两个 JSON 数组
- c++ - 在 Bison 和 Flex 中使用变体
- tensorflow - 自定义指标:使用 scikit learn 的 AucRoc Calculator 和 tf.keras
- r - 处理全国的 OSM 数据
- python-3.x - 启动时在 QcomboBox 中显示特定项目
- javascript - 如何将布尔值 true/false 或字符串“true”/“false”列入白名单
- python - 使用 setuptools 将模块安装到站点包
- r - 如何创建一个函数来计算单个单元中特定字符的共现次数?
- firebase-realtime-database - 如何在 POSTMAN 上向 Firebase Realtime DB 发送 HTTP GET 请求?
- javascript - 有没有办法绘制连接到正确数据的正确线?