选择行并根据条件SQL生成新列

时间:2016-11-08 12:45:20

标签: sql oracle select

我在Oracle中有以下表格

Company   Rate   Period
1A        10     sep-16
1B        20     sep-15
1C        30     oct-16
1D        40     sep-16
1A        50     oct-16
2B        50     sep-15
1C        60     oct-14

我想选择一些行并根据条件添加值。所以结果将类似于以下内容:

Company   Rate   Period    Currency
1A        50     oct-16    USD
1C        30     oct-16    AED

在上表中,我只选择公司1A,1C,其中Period =' oct-16'。我需要添加一个列"货币"对于每个公司,其中1A = USD,1C = AED

我做的是:

select company, PERIOD , Rate 
from TABLE_test 
where period='Oct-16' And Company='1A' 
    OR period='Oct-16' and Company='1C';

我成功获得了这些公司,但在货币栏中失败了。这可能使用SQL命令吗?请帮忙。

3 个答案:

答案 0 :(得分:2)

select company, PERIOD , Rate,
(CASE WHEN Company ='1A' THEN 'USD' WHEN Company ='1C' THEN 'AED'  END) "Currency"
from TABLE_test where...

答案 1 :(得分:2)

是的,可以使用案例条件:

    SELECT COMPANY,RATE,PERIOD,(CASE WHEN COMPANY='1A' THEN 'USD' 
                                     WHEN COMPANY='1C' THEN 'AED' END
                                    )CURRENCY
    FROM TABLE_TEST
    WHERE PERIOD='oct-16'
    AND COMPANY IN ('1A','1C')

答案 2 :(得分:1)

试试这个:

SELECT Company, Rate, Period, 
  CASE WHEN Company='1A' 
    THEN 'USD' 
    WHEN Company='1C' 
    THEN 'AED' 
  END as Currency
FROM TABLE_test
WHERE Period = 'oct-16'