2017-10-12 20 views
0

Ich Formatierung einer Datumsspalte in eine Zeichenfolge mit nur Jahr und Monat Namen wie untersortieren eine formatierte Datum Spalte als Datum

   WITH c1 as ( 
SELECT FORMAT(CompletedDate,'MMMM yyyy') as FormattedDate, 
COUNT(CASE WHEN CoId =5 then 1 ELSE NULL END) as "SSS", 
COUNT(CASE WHEN CoId =3 then 1 ELSE NULL END) as "EEE" 
    FROM Rtml5 
    where CompletedDate>='2017-01-01' AND CompletedDate<= '2017-12-31' 
group by FORMAT(CompletedDate,'MMMM yyyy') 
), 
c2 As (
    SELECT FORMAT(CompletedDate,'MMMM yyyy') as FormattedDate,COUNT(Rawew_ID) as MMM 
    FROM Rawew 
    where CompletedDate>='2017-01-01' AND CompletedDate<= '2017-12-31' 
group by FORMAT(CompletedDate,'MMMM yyyy') 
) 
SELECT coalesce(c1.FormattedDate, c2.FormattedDate) as FormattedDate, c1.SSS,c1.EEE,c2.MMM 
FROM c1 FULL OUTER JOIN c2 on c1.FormattedDate = c2.FormattedDate 

Und dann habe ich die Gruppe von FORMAT (CompletedDate "MMMM yyyy) auf diese formatierte Spalte ich erhalte Ergebnisse wie unten

April 2017 
    August 2017 
    February 2016 
    January 2017 
    July 2016 
    June 2017 
    March 2017 
    May 2017 
    October 2017 
    September 2017 

Aber wie kann ich dies als eine Datumsspalte selbst sortieren. Ich möchte die Ergebnisse in der Reihenfolge Februar 2016, Juli206, Januar 2017, Februar 2017 ....

+0

Versuchen Sie, auf 'CompletedDate' zu ​​sortieren. Was ist das Format von 'CompletedDate'? Bitte zeigen Sie uns Ihre komplette Anfrage – Sinto

+1

Beispieldaten & gewünschtes Ergebnis hinzufügen. –

Antwort

1

Reihenfolge von Jahr und Monat statt, müssen sie in der Gruppierung und cte Ergebnis auch sein.

WITH c1 as ( 
    SELECT FORMAT(CompletedDate,'MMMM yyyy') as FormattedDate, 
     datepart(year,CompletedDate) YearNr,datepart(month,CompletedDate) MonthNr 
     COUNT(CASE WHEN CoId =5 then 1 ELSE NULL END) as "SSS", 
     COUNT(CASE WHEN CoId =3 then 1 ELSE NULL END) as "EEE" 
    FROM Rtml5 
    where CompletedDate>='2017-01-01' AND CompletedDate<= '2017-12-31' 
    group by datepart(year,CompletedDate),datepart(month,CompletedDate), 
     FORMAT(CompletedDate,'MMMM yyyy') 
    ), 
c2 As (
    SELECT FORMAT(CompletedDate,'MMMM yyyy') as FormattedDate,COUNT(Rawew_ID) as MMM, 
     datepart(year,CompletedDate) YearNr,datepart(month,CompletedDate) MonthNr 
    FROM Rawew 
    where CompletedDate>='2017-01-01' AND CompletedDate<= '2017-12-31' 
    group by datepart(year,CompletedDate),datepart(month,CompletedDate), 
     FORMAT(CompletedDate,'MMMM yyyy') 
) 

SELECT coalesce(c1.FormattedDate, c2.FormattedDate) as FormattedDate, c1.SSS,c1.EEE,c2.MMM 
FROM c1 
FULL OUTER JOIN c2 on c1.FormattedDate = c2.FormattedDate 
order by coalesce(c1.YearNr,c2.YearNr),coalesce(c1.MonthNr,c2.MonthNr) 
+0

Bitte lesen Sie meine vollständige Abfrage, wie ich das Format verwende, um das Datum in einer formatierten Weise anzuzeigen, –

+0

@JibinMathew Ich habe die Antwort mit Ihrer Abfrage aktualisiert. – Peter