我做了一个简单的例子来更好地理解我的问题是什么。
所以,我有2个表,我有一个基于inner join
的选择,这是一个选择。
create table students(
id_student number,
name_student varchar2(15),
id_advisor number,
money number
);
insert into students values(1, 'Student_1', 1, 100);
insert into students values(2, 'Student_2', 8,-200);
insert into students values(4, 'Student_4', 7, 256);
insert into students values(5, 'Student_5', 3, -305);
----------------
create table advisors(
id_advisor number,
name_advisor varchar2(15)
);
insert into advisors values(1, 'advisor_1');
insert into advisors values(3, 'advisor_3');
insert into advisors values(5, 'advisor_5');
------------------------------------------
SELECT name_advisor, money as money_pozitive
FROM(
select name_student, name_advisor, money from students
inner join advisors on students.id_advisor = advisors.id_advisor)
WHERE money > 0
使用此代码,我得到以下结果:
name_advisor | money_pozitive
------------------------------------
advisor_1 | 100
我的问题是,我如何添加名为money_negative
的额外列,当然还有负值?像这样:
name_advisor | money_pozitive | money_negative
---------------------------------------------------------
advisor_1 | 100 | -305
答案 0 :(得分:4)
只需使用case
:
select name_student, name_advisor,
(case when money > 0 then money end) as money_positive,
(case when money < 0 then money end) as money_negative
from students s inner join
advisors a
on s.id_advisor = a.id_advisor;
注意:
where
条款。