得到一个序列,忽略Nulls

时间:2016-08-03 15:07:14

标签: sql hana

我有下表,在哪里?是空值。

X14 X13 X12 X11 X10 X9  X8  X7  X6
9   ?   ?   ?   ?   1   17  14  ?
8   9   ?   ?   ?   1   17  14  ?
1   8   9   ?   ?   1   17  14  ?
?   1   8   1   9   1   17  14  ?
?   ?   1   ?   9   1   17  14  ?
?   ?   ?   ?   ?   8   9   2   14

我试图在没有Null的情况下跨列来获取值[x(n),x(n-1),...]的序列。

预期结果如下:

y   x1  x2  x3
9   1   17  14
8   9   1   17
1   8   9   1
1   8   1   9
1   9   1   17
8   9   2   14

我尝试执行COALESCE(X14,COALESCE(X13,...)),但它不能很好地工作,因为它卡在它找到的第一个非空值上。

我能做些什么来跳过Null并获得正确的序列? 数据库是Hana,但无论如何都要分享你的答案 - 我可能能够适应它。 :)

最佳,
米格尔

3 个答案:

答案 0 :(得分:2)

可能与SQL Server有关,但有一个XML技巧:

XML - 默认情况下 - 只省略NULLs

其他数据库(在你的情况下是 hana )不支持这个,但你可能会有一个想法......

这会带来您需要的结果。

DECLARE @tbl TABLE(X14 INT,X13 INT,X12 INT,X11 INT,X10 INT,X9 INT,X8 INT,X7 INT,X6 INT);
INSERT INTO @tbl VALUES
 (9,NULL,NULL,NULL,NULL,1,17,14,NULL)
,(8,9,NULL,NULL,NULL,1,17,14,NULL)
,(1,8,9,NULL,NULL,1,17,14,NULL)
,(NULL,1,8,1,9,1,17,14,NULL)
,(NULL,NULL,1,NULL,9,1,17,14,NULL)
,(NULL,NULL,NULL,NULL,NULL,8,9,2,14);

WITH Casted AS
(SELECT
    (
        SELECT *
        FROM @tbl
        FOR XML PATH('row'),TYPE
    ) AS AsXml
)
SELECT r.value('*[1]','int') AS y
      ,r.value('*[2]','int') AS x1
      ,r.value('*[3]','int') AS x2
      ,r.value('*[4]','int') AS x3
FROM Casted
CROSS APPLY AsXml.nodes('/row') AS A(r)

答案 1 :(得分:2)

create column  TABLE xvals (X14 INT,X13 INT,X12 INT,X11 INT,X10 INT,X9 INT,X8 INT,X7 INT,X6 INT);

INSERT INTO xvals (
select 9,NULL,NULL,NULL,NULL,1,17,14,NULL from dummy UNION ALL
select 8,9,NULL,NULL,NULL,1,17,14,NULL from dummy UNION ALL
select 1,8,9,NULL,NULL,1,17,14,NULL from dummy UNION ALL
select NULL,1,8,1,9,1,17,14,NULL from dummy UNION ALL
select NULL,NULL,1,NULL,9,1,17,14,NULL from dummy UNION ALL
select NULL,NULL,NULL,NULL,NULL,8,9,2,14 from dummy 
);

with aschar as (
    select ifnull(to_varchar(X14)||'x', '') ||
           ifnull(to_varchar(X13)||'x', '') ||
           ifnull(to_varchar(X12)||'x', '') ||
           ifnull(to_varchar(X11)||'x', '') ||         
           ifnull(to_varchar(X10)||'x', '') ||         
           ifnull(to_varchar(X9)||'x', '') ||
           ifnull(to_varchar(X8)||'x', '') ||
           ifnull(to_varchar(X7)||'x', '') ||
           ifnull(to_varchar(X6)||'x', '')           
           cval
    from xvals)

select  SUBSTR_REGEXPR ('[[:digit:]]+' in cval occurrence 1)
            as y,
        SUBSTR_REGEXPR ('[[:digit:]]+' in cval occurrence 2)
            as x1,
        SUBSTR_REGEXPR ('[[:digit:]]+' in cval occurrence 3)
            as x2,
        SUBSTR_REGEXPR ('[[:digit:]]+' in cval occurrence 4)
            as x3

from aschar

Y   X1  X2  X3
9   1   17  14
8   9   1   17
1   8   9   1 
1   8   1   9 
1   9   1   17
8   9   2   14

答案 2 :(得分:0)

将它们放在四个单独的列中很困难。您可以将有效值连接到一个列表中:

select (case when x14 is not null then x14 || ';' else '' end) ||
       (case when x13 is not null then x13 || ';' else '' end) ||
       . . .