如何访问第一个 select 语句的输出

How can I acces the output from the first select statement

我有一个table像这样

Col1 | Col2
-----------
a    | d
b    | e
c    | a

现在我想创建一个语句来获得这样的输出:

First| Second
-------------------
a    | Amsterdamm
b    | Berlin
c    | Canada
...

到目前为止,我的这个构造不起作用

SELECT *
FROM(
    SELECT DISTINCT
        CASE
            when Col1 IS NULL then 'NA' 
            else Col1
        END
        FROM Table1
    UNION
        SELECT DISTINCT
        CASE
            when Col2 IS NULL then 'NA' 
            else Col2
        END
    FROM Table1
    ) AS First
    ,
    (   
    SELECT DISTINCT
        when First= 'a' then 'Amsterdam'
        when First= 'b' then 'Berlin'
        when First= 'c' then 'Canada'
    ) AS Second
;

你能帮我吗

抱歉,我必须编辑我的问题以使其更具体。

不太熟悉 DB2...如果它有 concat function,我会在几秒钟内查找...它确实有。

SELECT First, case when first = 'a' then 
                    concat('This is a ',first)
              case when first = 'b' then 
                    concat('To Be or not to ',first)
              case else  
                    concat('This is a ',first) end  as Second
FROM (
  SELECT coalesce(col1, 'NA') as First 
  FROM Table
  UNION
  SELECT coalesce(col2, 'NA') 
  FROM table) SRC
WHERE first <> 'NA'

这样做是生成一个名为 src 的内联视图,其中包含一个名为 first 的列。如果 tablecol1col2 为空,则用 NA 代替该值。然后它连接 first 和所需的文本,不包括 first 值为 'NA'

的记录

或者,如果您只是创建一个具有所需值的内联 table 并加入...

    SELECT First,  x.b as Second
    FROM (
      SELECT coalesce(col1, 'NA') as First 
      FROM Table
      UNION
      SELECT coalesce(col2, 'NA') 
      FROM table) SRC
    INNER JOIN (select a,b 
                from (values ('a', 'This is a'), 
                             ('b', 'To B or not to' ), 
                             ('c', 'I like cat whose name starts with')) as x(a,b)) X;
   on X.a = src.first
    WHERE first <> 'NA'

我个人觉得第二个选项更容易阅读。虽然如果你对 a、b、c 有意义,我认为你会希望将其存储在 table 某处以供额外访问。在代码中存储这样可能会更改的数据似乎不是一个好地方。 假设你想要

a this is a a 
b this is a b 
c this is a c 
d this is a d
e this is a e

感谢 xQbert 我可以这样解决这个问题

SELECT FirstRow, concat
(
CASE FirstRow
WHEN 'AN' then 'amerstdam'
WHEN 'G' then 'berlin'
ELSE 'NA'
END, ''
) AS SecondRow
FROM(
    Select coalesce (Col1, 'NA') as FirstRow 
    FROM Table1
    UNION
    Select coalesce (Col2, 'NA')
    FROM Table1) SRC
WHERE FirstRow <> 'NA'
;