在oracle中进行条件选择的最佳方法是什么?

时间:2013-11-14 16:39:30

标签: sql oracle plsql oracle11g

我是sql的新手,对不起,这可能是非常基本的。

我有一张名为T1的表

T1
ID   Group Entity Percentage  Long_Term   Short_Term
1    AAA    BBB      99%      Long    
2    CCC    DDD      99%                  Short
3    EEE             99%      Long
4           FFF      99%                  Short

插入T2

ID   Name   Classification   Percentage  Term

如果Group和Entity都不为null,则只需选择Entity。 所以想要的T2将是:

ID   Name   Classification   Percentage  Term
1  BBB      Entity              99       Long
2  DDD      Entity              99       Short
3  EEE      Group               99       Long
4  FFF      Entity              99       Short

如何从T1中选择并像T2一样插入T2。 谢谢!

2 个答案:

答案 0 :(得分:0)

DECODE功能在这里会有所帮助。我们检查Entity是否为NULL,如果是,请从Group列中取值。我们对classification也这样做,但在这里我们提供文字值作为结果。我看到你对Term列也想要同样的事情了吗?

CREATE TABLE t1 (
  id NUMBER,
  group_val VARCHAR2(3),
  entity VARCHAR2(3),
  percentage VARCHAR2(4),
  long_term VARCHAR2(20),
  short_term VARCHAR2(20)
);

INSERT INTO t1 VALUES (1, 'AAA', 'BBB', '99%', 'Long', NULL);
INSERT INTO t1 VALUES (2, 'CCC', 'DDD', '99%', NULL, 'Short');
INSERT INTO t1 VALUES (3, 'EEE', NULL, '99%', 'Long', NULL);
INSERT INTO t1 VALUES (4, NULL, 'FFF', '99%', NULL, 'Short');

COMMIT;

CREATE TABLE t2 AS
  SELECT
      id,
      DECODE(entity, NULL, group_val, entity) AS name,
      DECODE(entity, NULL, 'Group', 'Entity') AS classification,
      percentage,
      DECODE(long_term, NULL, short_term, long_term) AS term
  FROM
    t1;

SELECT * FROM t2;
        ID NAME CLASSIFICATION PERCENTAGE TERM               
---------- ---- -------------- ---------- --------------------
         1 BBB  Entity         99%        Long                 
         2 DDD  Entity         99%        Short                
         3 EEE  Group          99%        Long                 
         4 FFF  Entity         99%        Short 

如果您已经有t2表,那么:

INSERT INTO t2
  SELECT
      id,
      DECODE(entity, NULL, group_val, entity) AS name,
      DECODE(entity, NULL, 'Group', 'Entity') AS classification,
      percentage,
      DECODE(long_term, NULL, short_term, long_term) AS term
  FROM
    t1;

检查 SQLFiddle

答案 1 :(得分:0)

您可以使用COALESCE(或NVL)和CASE子句执行此操作:

select 
  id, 
  coalesce(groupid, entity) as name,
  case when entity is not null then 'Entity' else 'Group' end as classification,
  percentage, 
  coalesce(long_term, short_term) as term
from  t1;

BTW:不要打电话给您的专栏GROUP。 GROUP是一个SQL词。