我是DB2
的新手。所以,请忍受我。以下是用于获取数据的查询。目的是在未找到任何内容的情况下设置“默认”值:
查询:
SELECT t1.col1,t1.col2,t1.col3,t1.col4,t1.col5 FROM TABLE t1 FETCH FIRST 5 ROWS ONLY;
我尝试过的事情:
SELECT t1.col1,t1.col2,t1.col3,t1.col4 SET DEFAULT 'Data Missing',t1.col5 FROM TABLE t1 FETCH FIRST 5 ROWS ONLY;
SELECT t1.col1,t1.col2,t1.col3,COALESCE(t1.col4 SET,'Data Missing'),t1.col5 FROM TABLE t1 FETCH FIRST 5 ROWS ONLY;
SELECT t1.col1,t1.col2,t1.col3,COALESCE(t1.col4 SET,0),t1.col5 FROM TABLE t1 FETCH FIRST 5 ROWS ONLY;
SELECT t1.col1,t1.col2,t1.col3,t1.col4 NOT NULL DEFAULT 'Data Missing',t1.col5 FROM TABLE t1 FETCH FIRST 5 ROWS ONLY;
但是,这些都不起作用。
在MySQL中,我可以通过以下方法实现相同目的:
SELECT t1.col1,t1.col2,t1.col3,t1.col4 NOT NULL DEFAULT 'Data Missing', t1.col5 FROM TABLE t1 LIMIT 5;
Update_1:在下面尝试过
select col1,
case
when col4 is null then 'Data Missing' else col4 end as col4
when col3 is null then 'Data Missing' else col3 end as col3
when col2 is null then 'Data Missing' else col2 end as col2
from my_table
fetch first 5 rows only;
错误:
1) [Code: -104, SQL State: 42601] An unexpected token "WHEN" was found following "END AS COL4
". Expected tokens may include: "INTO".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.22.29
2) [Code: -727, SQL State: 56098] An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-104", SQLSTATE "42601" and message tokens "WHEN|END AS COL4
答案 0 :(得分:3)
假设col4是char类型:
select
col1, col2, col3, coalesce(col4, 'Data Missing') as col4
from my_table
fetch first 5 rows only
更通用的按摩数据解决方案可以是:
select
col1, col2, col3,
case
when col4 is null then 'Data Missing'
-- you can add more "when" cases here.
else col4
end as col4
from my_table
fetch first 5 rows only
答案 1 :(得分:1)
我还不能添加评论。.关于您的“ Update_1”,您忘记了用逗号分隔列(并重复CASE词),因此应显示为:
select col1,
case when col4 is null then 'Data Missing' else col4 end as col4,
case when col3 is null then 'Data Missing' else col3 end as col3,
case when col2 is null then 'Data Missing' else col2 end as col2
from my_table
fetch first 5 rows only;
或者简单地
select col1,
COALESCE(col4, 'Data Missing') as col4,
COALESCE(col3, 'Data Missing') as col3,
COALESCE(col2, 'Data Missing') as col2
from my_table
fetch first 5 rows only;