[英]SQL Server ORDER BY when using DATENAME function
SELECT CAST(DATEPART(yyyy,DATE1)
AS varchar (5)) + '-' + CAST(DATENAME(m,ec2.DATE2)
AS varchar(3)) AS [Month],
CAST(AVG(CAST(DATEDIFF(day,DATE1, DATE2)
AS DECIMAL(10,2))) AS DECIMAL(10,2)) AS tt
FROM tbl3
GROUP BY CAST(DATEPART(yyyy,DATE1) AS
varchar (5)) + '-' + CAST(DATENAME(m,ec2.DATE2)
AS varchar(3))
ORDER BY [Month]
So in the above query I have results for 2 different years so its sorting year in integer wise but Month according to alphabets(as its DATENAME
) Examples: 因此,在上面的查询中,我得到了2个不同年份的结果,因此以整数形式对年份进行排序,但是根据字母(作为其
DATENAME
)显示Month的示例:
2013-Dec 4.45
2013-Nov 5.55
2014-Jan 2.35
2014-Jan 2-85
The problem is I am using DATE2
in my aggregate function( Avg
) and hence can't use it in ORDER BY
clause. 问题是我在聚合函数(
Avg
)中使用了DATE2
,因此无法在ORDER BY
子句中使用它。
Anyone has a solution for this problem. 任何人都有解决此问题的方法。 I will be really thankful if you can help me.
如果您能帮助我,我将非常感谢。 I read other questions regarding this problem but didn't find the solution.
我阅读了有关此问题的其他问题,但没有找到解决方案。
Thanks in advance. 提前致谢。
A convoluted way, but works in any situation. 复杂的方式,但是在任何情况下都可以使用。 Use CTE to solve your issue as below:
使用CTE解决您的问题,如下所示:
With CTE as (
SELECT CAST(DATEPART(yyyy,DATE1)
AS varchar (5)) + '-' + CAST(DATENAME(m,ec2.DATE2)
AS varchar(3)) AS [Month],
CAST(AVG(CAST(DATEDIFF(day,DATE1, DATE2)
AS DECIMAL(10,2))) AS DECIMAL(10,2)) AS tt
FROM tbl3
GROUP BY CAST(DATEPART(yyyy,DATE1) AS
varchar (5)) + '-' + CAST(DATENAME(m,ec2.DATE2)
AS varchar(3))
Select * from CTE
ORDER BY
DATEPART(yyyy, cast([Month] as datetime)),
DATEPART(mm, cast([Month] as datetime));
I agree you can order by Year/Month as Darius X suggested. 我同意您可以按照Darius X的建议按年/月订购。 You can also use a cross apply to "wrap" your calculation.
您还可以使用交叉应用来“包装”您的计算。 Not sure it would solve your specfic problem, but for additional information.
不确定是否可以解决您的特定问题,但需要其他信息。 I figure out the MatchStatus in the CROSS APPLY then use MatchStatus in the SELECT & GROUP BY clauses.
我在CROSS APPLY中找出MatchStatus,然后在SELECT&GROUP BY子句中使用MatchStatus。
SELECT
MatchStatus,
COUNT(*)
FROM MPI.ACTData.Matches
CROSS APPLY (SELECT CASE WHEN MatchScore >= 69 THEN 'Match'
ELSE 'Review' END MatchStatus) ms
GROUP BY MatchStatus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.