SQL拆分列

时间:2016-10-06 12:02:57

标签: sql sql-server

我做了一个简单的例子来更好地理解我的问题是什么。 所以,我有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

1 个答案:

答案 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条款。