0

我是 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 中。谢谢!

4

2 回答 2

0

You do this with COALESCE (or NVL) and a CASE clause:

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: Don't call your column GROUP. GROUP is an SQL word.

于 2013-11-14T17:49:57.527 回答
0

DECODE功能将在这里有所帮助。我们检查是否EntityIS 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 名称 分类 百分比 术语               
---------- ---- -------------- ---------- ------------ --------
         1 BBB 实体 99% 多头                 
         2 DDD 实体 99% 短                
         3 EEE 组 99% 长                 
         4 FFF 实体 99% 短

如果您已经有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

于 2013-11-14T16:52:55.337 回答