9

我有下面的表 A,其中对于每个唯一 ID,有三个具有某些值的代码。

 ID    Code    Value
---------------------
 11       1       x
 11       2       y
 11       3       z
 12       1       p
 12       2       q
 12       3       r
 13       1       l
 13       2       m
 13       3       n

我有第二个表 B,格式如下:

Id   Code1_Val   Code2_Val    Code3_Val

这里每个唯一 ID 只有一行。我想为第一个表中的每个 id 从第一个表 A 填充第二个表 B。

对于上面的第一个表 A,第二个表 B 应为:

Id   Code1_Val   Code2_Val    Code3_Val
---------------------------------------------
11       x          y             z
12       p          q             r
13       l          m             n

如何在单个 SQL 查询中实现这一点?

4

7 回答 7

9
   select Id,                                              
      max(case when Code = '1' then Value end) as Code1_Val,  
      max(case when Code = '2' then Value end) as Code2_Val,  
      max(case when Code = '3' then Value end) as Code3_Val   
      from TABLEA                                     
      group by Id                                            
于 2014-04-21T23:03:29.760 回答
3

如果你的版本没有DECODE(),你也可以使用这个:

INSERT INTO B (id, code1_val, code2_val, code3_val)  
WITH Ids (id) as (SELECT DISTINCT id
                  FROM A) -- Only to construct list of ids

SELECT Ids.id, a1.value, a2.value, a3.value
FROM Ids -- or substitute the actual id table
JOIN A a1
     ON a1.id = ids.id
        AND a1.code = 1
JOIN A a2
     ON a2.id = ids.id
        AND a2.code = 2
JOIN A a3
     ON a3.id = ids.id
        AND a3.code = 3

(适用于我的 V6R1 DB2 实例,并有一个SQL Fiddle Example)。

于 2012-11-27T19:37:48.353 回答
3
SELECT Id,
max(DECODE(Code, 1, Value)) AS Code1_Val,
max(DECODE(Code, 2, Value)) AS Code2_Val,
max(DECODE(Code, 3, Value)) AS Code3_Val
FROM A
group by Id
于 2016-11-06T12:22:07.250 回答
0

这是一个SQLFiddle 示例

insert into B (ID,Code1_Val,Code2_Val,Code3_Val)
select Id, max(V1),max(V2),max(V3) from
(
select ID,Value V1,'' V2,'' V3 from A where Code=1
union all
select ID,'' V1, Value V2,'' V3 from A where Code=2
union all
select ID,'' V1, '' V2,Value V3 from A where Code=3
) AG
group by ID
于 2012-11-27T07:23:07.400 回答
0

您想要透视您的数据。由于 DB2 没有数据透视函数,所以您可以使用 Decode(基本上是一个 case 语句。)

语法应该是:

SELECT Id,
   DECODE(Code, 1, Value) AS Code1_Val,
   DECODE(Code, 2, Value) AS Code2_Val,
   DECODE(Code, 3, Value) AS Code3_Val
FROM A
于 2012-11-27T07:27:05.763 回答
0

这是 SQL 查询:

insert into pivot_insert_table(id,code1_val,code2_val, code3_val) 
select * from (select id,code,value from pivot_table)
pivot(max(value) for code in (1,2,3)) order by id ;
于 2015-03-20T06:55:47.430 回答
0
 WITH Ids (id) as 
 (
  SELECT DISTINCT id FROM A
  )
 SELECT Ids.id, 
 (select sub.value from A sub where Ids.id=sub.id and sub.code=1 fetch first rows only) Code1_Val,

 (select sub.value from A sub where Ids.id=sub.id and sub.code=2 fetch first rows only) Code2_Val,

 (select sub.value from A sub where Ids.id=sub.id and sub.code=3 fetch first rows only) Code3_Val
 FROM Ids
于 2016-11-06T12:31:27.797 回答