2017-01-24 36 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