2017-10-12 74 views
0

我格式化日期列只有年份和月份名稱的字符串如下排序格式化的日期列日期

   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 

然後,我使用的組的格式(CompletedDate,「MMMM YYYY」)這個格式化列 我得到的結果如下

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

但我怎麼可以排序這是一個日期列本身。我想要的結果順序爲2016年2月,2016年7月,Januaty2017,2017年2月....

+0

嘗試對'CompletedDate'應用排序。 'CompletedDate'的格式是什麼?請向我們展示您的完整查詢 – Sinto

+1

添加樣本數據和期望的結果。 –

回答

1

按年份和月份排序,它們需要在分組和cte結果中。

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

請看看我的完整查詢,因爲我使用格式以格式化方式顯示日期, –

+0

@JibinMathew我已經使用您的查詢更新了答案。 – Peter