我有一张像这样的表
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
;
你可以帮我解决这个问题吗?
抱歉,我必须将我的问题编辑为更具体。
答案 0 :(得分:0)
不熟悉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
的列。如果col1
的{{1}}或col2
为空,则它会将NA替换为该值。然后,它会将table
和所需文字连接起来,排除first
值为“NA”的记录
或者,如果您只是创建一个包含所需值的内联表并加入...
first
就个人而言,我发现第二个选项更容易阅读。虽然如果你对a,b,c有意义,我会认为你想要存储在某个地方的表中以便进行额外的访问。在代码中似乎是一个存储可能会改变的数据的坏地方。 假设你想要
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'
答案 1 :(得分:0)
感谢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'
;