SQL Server 有没有一种方法可以从三列中选择一个值,然后添加一个关于哪些列为空的字符串,而不必对每个组合使用CASE?

s4n0splo  于 2023-01-16  发布在  其他
关注(0)|答案(1)|浏览(139)

我有三个专栏:我正在尝试编写一个查询,根据优先级显示三列中的一个值,因此只需要显示其中一列的值,优先级是description、name和id。
我的问题是,如果缺少描述或更多,则需要显示一条消息,说明第一个可用选项,后跟一段文本,其中包含有关空列或空列的信息。
示例:如果缺少描述,则应显示:name(未给出描述)如果缺少名称和描述,则应显示:id(未给出名称和描述)如果缺少代码、名称和描述,则应显示:未给出ID、名称和说明
最好,它应该能够处理id和description缺失的情况,或者只有name缺失的情况,并且理想情况下还可以扩展到三列以上。
你会怎么做呢?我试着对每一个组合都使用CASE语句,但如果扩展到三列以上,那很快就会成为一个问题,所以我想知道是否有更聪明的解决方案?
先谢了!

jgwigjjp

jgwigjjp1#

您可能需要一个CASE表达式,但它不需要很复杂:

coalesce(description, name, id) + 
    case when description is not null then ''
         when name is not null then ' (Description not given)'
         else ' (Name and description not given)' end

从这里开始,只需将每个附加列添加到coalesce()调用和case表达式中的另一个when行:

coalesce(description, name, id, foo) + 
    case when description is not null then ''
         when name is not null then ' (Description not given)'
         when id is not null then ' (Name and description not given)'
         else ' (Name, description, and id not given)' end

相关问题