0

我有三个 select 语句,每个语句都返回一个键和一列数据:

KEY     DATA_1
------- -------
A       123
B       456

KEY     DATA_2
------- -------
B       987
C       654
D       321

KEY     DATA_3
------- -------
D       234
E       567

我怎样才能:

a) 将三个数据列合并为一个结果集:

KEY     DATA_1   DATA_2  DATA_3
------- -------- ------- -------
A       123      NULL    NULL 
B       456      NULL    NULL
B       NULL     987     NULL
C       NULL     654     NULL
D       NULL     321     NULL
D       NULL     NULL    234
E       NULL     NULL    567

b) 合并行,使每个键只出现一次,每列中都有适当的数据值。

KEY     DATA_1   DATA_2  DATA_3
------- -------- ------- -------
A       123      NULL    NULL 
B       456      987     NULL
C       NULL     654     NULL
D       NULL     321     234
E       NULL     NULL    567

c) 将 NULL 值替换为我选择的值,例如“000”

KEY     DATA_1   DATA_2  DATA_3
------- -------- ------- -------
A       123      000     000
B       456      987     000
C       000      654     000
D       000      321     234
E       000      000     567
4

2 回答 2

1

让我们按顺序回答这个问题。

对于 1:

select key, data_1, data_2, data_3
from ((select key, data_1, NULL as data_2, NULL as data_3
       from t1
      ) union all
      (select key, NULL, data_2, NULL
       from t2
      ) union all
      (select key, NULL, NULL, data_3
       from t3
      )
     ) t

对于 2:

select key, max(data_1), max(data_2), max(data_3)
from ((select key, data_1, NULL as data_2, NULL as data_3
       from t1
      ) union all
      (select key, NULL, data_2, NULL
       from t2
      ) union all
      (select key, NULL, NULL, data_3
       from t3
      )
     ) t
group by key;

对于 3:

select key, coalesce(max(data_1), '000'),
       coalesce(max(data_2), '000'), coalesce(max(data_3), '000')
from ((select key, data_1, NULL as data_2, NULL as data_3
       from t1
      ) union all
      (select key, NULL, data_2, NULL
       from t2
      ) union all
      (select key, NULL, NULL, data_3
       from t3
      )
     ) t
group by key;

最后一个示例假设数据值是字符串。否则,'000'将转换为数字 0。

于 2013-05-22T13:46:10.393 回答
0

尝试:

 SELECT k.[key],
       Max(COALESCE(s1.data_1, '000')) data_1,
       Max(COALESCE(s2.data_2, '000')) data_2,
       Max(COALESCE(s3.data_3, '000')) data_3
FROM   (SELECT [key]
        FROM   select1
        UNION
        SELECT [key]
        FROM   select2
        UNION
        SELECT [key]
        FROM   select3) k
       LEFT JOIN select1 s1
              ON k.[key] = s1.[key]
       LEFT JOIN select2 s2
              ON k.[key] = s2.[key]
       LEFT JOIN select3 s3
              ON k.[key] = s3.[key]
GROUP  BY k.[key]  

根据data_*字段类型(数字或 varchar)和数据库引擎,可能需要进行一些调整。

注意 :key是一个 SQL 保留关键字。

于 2013-05-22T13:44:39.580 回答