逗号分隔的行值列表

Comma delimited list of row values

我目前的数据库结构与此类似:

Name | v_BirthDate | v_Drivers_License | v_SSN 
-----------------------------------------------
Anna |      1      |         0         |   1
Bob  |      0      |         1         |   0
Cal  |      1      |         1         |   1 
Dave |      0      |         0         |   1

数据库的基本思想是看这个人在系统中是如何被验证的;此人是否已在系统中使用出生日期、驾照号码或社交账号进行验证。

我想做的是为每个人取一行并创建另一列以逗号分隔格式显示所用验证方法的列表。

与此类似的内容:

Name | v_BirthDate | v_Drivers_License | v_SSN |    list 
-----------------------------------------------------------
Anna |      1      |         0         |   1   | BirthDate,SSN
Bob  |      0      |         1         |   0   | Drivers_License
Cal  |      1      |         1         |   1   | BirthDate,Drivers_License,SSN
Dave |      0      |         0         |   1   | SSN

我使用 WITH 子句创建了一个临时 table,将 1 更改为字符串变量,例如 BirthDate、Drivers_License 和 SSN。但是,我不确定如何创建列表列。提前谢谢你。

你可以用一个巨大的 case 和一些字符串逻辑来做到这一点:

select t.*,
       trim(leading ',' from
            (case when v_BirthDate = 1 then ',BirthDate' else '' end) ||
            (case when v_Drivers_License = 1 then ',Drivers_License' else '' end) ||
            (case when v_SSN = 1 then ',v_SSN' else '' end)
           ) as list
from t;

这将创建一个由每个组件组成的字符串,每个组件前面都有一个逗号。 trim() 删除开头的逗号。

我会做类似的事情:

with x as (
  select
      name, v_birthdate, v_drivers_license, v_ssn,
      case when v_birthdate = 1 then ',BirthDate' else '' end ||
      case when v_drivers_license = 1 then ',Drivers_License' else '' end ||
      case when v_ssn = 1 then ',SSN' else '' end as list
    from my_table
)
select 
    name, v_birthdate, v_drivers_license, v_ssn,
    case when list = '' then list else substr(list, 2) end as list
  from x;