Query

如何從單個列中檢索“y”和“n”逗號分隔值作為“是”或“否”

  • October 29, 2018

我在數據庫中有一個包含這些列的表

id     name    facility_Type
1      Taluka    y,n,n,y,n

現在我想像這樣檢索逗號分隔的值

id      name     Ambulance   ward  male_doctors  female_doctors  operation_theator
1    Taluka      yes         no      no             yes              no          

一些數據庫會支持這樣的東西(Oracle、MySQL、PostgreSQL、SQLite)。

select T.id,
      T.name,
      case substr(T.facility_type, 1, 1) when 'y' then 'yes' else 'no' end as Ambulance,
      case substr(T.facility_type, 3, 1) when 'y' then 'yes' else 'no' end as ward,
      case substr(T.facility_type, 5, 1) when 'y' then 'yes' else 'no' end as male_doctors,
      case substr(T.facility_type, 7, 1) when 'y' then 'yes' else 'no' end as female_doctors,
      case substr(T.facility_type, 9, 1) when 'y' then 'yes' else 'no' end as operation_theator
from T;

如果您在 SQL Server 上,則需要輸入substring.

select T.id,
      T.name,
      case substring(T.facility_type, 1, 1) when 'y' then 'yes' else 'no' end as Ambulance,
      case substring(T.facility_type, 3, 1) when 'y' then 'yes' else 'no' end as ward,
      case substring(T.facility_type, 5, 1) when 'y' then 'yes' else 'no' end as male_doctors,
      case substring(T.facility_type, 7, 1) when 'y' then 'yes' else 'no' end as female_doctors,
      case substring(T.facility_type, 9, 1) when 'y' then 'yes' else 'no' end as operation_theator
from T;

引用自:https://dba.stackexchange.com/questions/51937