gpt4 book ai didi

SQL 组合列字符串

转载 作者:行者123 更新时间:2023-12-04 04:53:06 24 4
gpt4 key购买 nike

我有一个如下所示的 sql 表

p1   c1   c2    c3     c4    c5    c6    c7
A B C D E F NULL NULL
A B C NULL NULL NULL NULL NULL
A B NULL NULL NULL NULL NULL NULL
A NULL NULL NULL NULL NULL NULL NULL

我需要一个带有 1 列的 select sql 查询,输出看起来像
Result
A > B > C > D > E > F
A > B > C
A

我尝试了嵌套的选择案例,但是我只得到了空值
select 
case when x.p1 IS not NULL then(
x.p1 + case when x.c1 IS not NULL then(
' > '+ x.c1 + case when x.c2 IS not NULL then(
' > '+ x.c2 + case when x.c3 IS not NULL then(
' > '+ x.c3 + case when x.c4 IS not NULL then(
' > '+ x.c4 + case when x.c5 IS not NULL then(
' > '+ x.c5 + case when x.c6 IS not NULL then(
' > '+ x.c6 + case when x.c7 IS not NULL then(
' > '+ x.c7 )end )end )end )end )end )end )end) end as tree
from mytable
  • 有没有更好的方法来获得我想要的结果?
  • 我的选择案例有什么问题?
  • 最佳答案

    基于在 TSQL 'a string' + null 中的事实等于 null ,您可以将查询简化为:

    select 
    p1
    + isnull(('>' + c1), '')
    + isnull(('>' + c2), '')
    + isnull(('>' + c3), '')
    + isnull(('>' + c4), '')
    + isnull(('>' + c5), '')
    + isnull(('>' + c6), '')
    + isnull(('>' + c7), '')
    from mytable

    SQLFiddle 链接: http://www.sqlfiddle.com/#!3/02b05/8

    what is wrong with my select case?



    您正在使用表别名 x似乎没有在任何地方定义。

    我分两步完成了您的查询:
  • 定义 x表别名。为此,只需写 mytable x最后而不是仅仅 mytable
  • 在上述修复之后,它仍然会返回 null,因为 case语句只有一个分支,当条件不满足时,它们仍然返回 null .要解决这个问题,请更换每个 endelse '' end (返回空字符串而不是 null )

  • 这是您的版本: http://www.sqlfiddle.com/#!3/02b05/11

    关于SQL 组合列字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17132414/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com