我有一個有趣的查詢,其中包含錯誤的聚合命令,因爲它以字母順序排列日期,因爲它們是字符串(VARCHARS)。它如下。SQL order by concatenated Month and Year字符串
DROP PROCEDURE dbo.DeploymentReport
GO
CREATE PROCEDURE dbo.DeploymentReport
@Date DATE
AS
BEGIN
SELECT TOP 6 DATENAME(MONTH,DeployDate) + ' - ' + DATENAME(YEAR,DeployDate) AS 'Month',
ISNULL(SUM(CASE WHEN OverallRiskRating = 3 THEN 1 END),0) AS 'High',
ISNULL(SUM(CASE WHEN OverallRiskRating = 2 THEN 1 END),0) AS 'Med',
ISNULL(SUM(CASE WHEN OverallRiskRating = 1 THEN 1 END),0) AS 'Low'
FROM dbo.ChangeEvaluationForm cef
INNER JOIN dbo.Package pac
ON cef.ChangeId = pac.ChangeId
INNER JOIN dbo.SDMTicket sdm
ON pac.PackageId = sdm.PackageId
WHERE DeployDate < @Date
GROUP BY DATENAME(MONTH, DeployDate) + ' - ' + DATENAME(YEAR,DeployDate)
ORDER BY DATENAME(MONTH, DeployDate) + ' - ' + DATENAME(YEAR,DeployDate) DESC
END
GO
DECLARE @DateSelected DATETIME
SET @DateSelected = CONVERT(DATE,'2017-12-30')
EXECUTE dbo.DeploymentReport @Date = @DateSelected;
結果如下所示
正如你所看到的月份按日期排序的字母數字代替。
現在我對彙總查詢是絕對殘酷的,所以我的鬥爭是改變ORDER BY行,以便以某種方式解析「月」列中的年份和月份,以及年份和月份中的訂單,而不更改數據返回的結構。
這是不是可能,或者是我認爲不可能的方法或者錯誤的思維方式?
只是不按DATENAME命令。只需使用「ORDER BY DATEPART(mm,DeployDate)」等等 –