2017-01-24 39 views
-5

當前,我有一個查詢使用多個CASE語句,如果兩個日期值之間存在匹配,則返回1。然而,不是隻有1和0的多列,我希望能夠返回所有字段名稱的值爲1到每行的新列。此外,我使用SQL Server 2014返回列表到所有匹配的新列

 
+--------------+-------------+---------------+ 
| DateVerified | DateCreated | DateInactive | 
+--------------+-------------+---------------+ 
|   1 |   0 |    0 | 
|   0 |   1 |    1 | 
|   1 |   0 |    1 | 
+--------------+-------------+---------------+ 
 
+---------------------------+ 
| Matches     | 
+---------------------------+ 
| DateVerified    |   
| DateCreated,DateInactive |   
| DateVerified, DateInactive|   
+---------------------------+ 

+0

您的查詢在哪裏?你使用的樣本數據怎麼樣?表結構等 –

回答

0

你可以做這樣的事情:

select 
case DateVerified when 0 then '' else 'DateVerified ' end + 
case DateCreated when 0 then '' else 'DateCreated ' end + 
case DateInactive when 0 then '' else 'DateInactive ' end Matches 
from dataTable 

如果逗號是很重要的你:

select case when len(Matches) > 0 then left(Matches,len(Matches)-1) else Matches end Matches 
from (
    select *, 
    case DateVerified when 0 then '' else 'DateVerified,' end + 
    case DateCreated when 0 then '' else 'DateCreated,' end + 
    case DateInactive when 0 then '' else 'DateInactive,' end Matches 
    from dateTable 
) t 
0

我不不知道爲什麼你想要這樣的東西,但在這種情況下,你需要使用CASE聲明:

 SELECT 
     CASE WHEN DateVerified = 1 and DateCreated = 1 and DateInactive = 1 THEN 'DateVerified,DateCreated,DateInactive' 
      WHEN DateVerified = 1 and DateCreated = 1 and DateInactive = 0 THEN 'DateVerified,DateCreated' 
      WHEN DateVerified = 1 and DateCreated = 0 and DateInactive = 0 THEN 'DateVerified' 
      WHEN DateVerified = 1 and DateCreated = 0 and DateInactive = 1 THEN 'DateVerified, DateInactive' 
      WHEN DateVerified = 0 and DateCreated = 1 and DateInactive = 1 THEN 'DateCreated, DateInactive' 
      WHEN DateVerified = 0 and DateCreated = 0 and DateInactive = 1 THEN 'DateInactive' 
      WHEN DateVerified = 0 and DateCreated = 1 and DateInactive = 0 THEN 'DateCreated ' 
     END AS Matches 

    FROM table 
+0

如果你需要添加更多的日期字段到混音,這將變得很難看。 – Jerrad

+0

完全同意,但我沒有看到任何其他方式從SQL Server做到這一點,而無需創建存儲過程。 –

+0

除了我的回答下面? :) – Jerrad