2017-01-24 3 views
-5

Derzeit habe ich eine Abfrage, die mehrere CASE-Anweisungen verwendet, die eine 1 zurückgeben, wenn eine Übereinstimmung zwischen zwei Datumswerten vorliegt. Anstatt jedoch mehrere Spalten mit nur 1 und 0 zu haben, möchte ich in der Lage sein, alle Feldnamen mit dem Wert 1 in eine neue Spalte für jede Zeile zurückzugeben. Auch ich bin mit SQL Server 2014.Rückgabeliste in neue Spalte aller Übereinstimmungen

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

+0

wo ist Ihre Suchanfrage, die Sie verwenden? Was ist mit Beispieldaten, die Sie verwenden? Tabellenstruktur usw. –

Antwort

0

Man könnte so etwas tun:

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 

Wenn Kommas für Sie wichtig sind:

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

I don‘ Ich weiß, warum Sie so etwas so wollen, aber in diesem Fall müssen Sie eine CASE Anweisung verwenden:

 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

Dies wird schnell hässlich, wenn Sie dem Mix mehr Datumsfelder hinzufügen müssen. – Jerrad

+0

Stimmen Sie vollkommen zu, aber ich sehe keine andere Möglichkeit, dies von SQL Server aus zu tun, ohne eine gespeicherte Prozedur zu erstellen. –

+0

Anders als meine Antwort unten? :) – Jerrad

Verwandte Themen