我的SQL查询是:
SELECT DISTINCT
SUBSTRING(DATENAME(MONTH, PostDate), 1, 3) + '-' + CAST(YEAR(PostDate) AS VARCHAR(4)) AS PostArchive,
Posts = COUNT(*)
FROM
Post WHERE Verified=1
GROUP BY
SUBSTRING(DATENAME(MONTH, PostDate), 1, 3) + '-' + CAST(YEAR(PostDate) AS VARCHAR(4)),
YEAR(PostDate), MONTH(PostDate)
ORDER BY PostArchive
它给出了这样的结果:
PostArchive Posts ------------------------ Mar-2009 1 Mar-2010 1 May-2005 1 May-2011 1 May-2012 1 May-2013 1
但是我希望按照日期(年)的顺序排列结果。
PostArchive Posts ------------------------ May-2005 1 Mar-2009 1 Mar-2010 1 May-2011 1 May-2012 1 May-2013 1
我搜索并找到this链接,但无法解决我的问题。
我试试:
ORDER BY CONVERT(DateTime, PostArchive,101) DESC
但它给了我一个错误:
Invalid column name 'PostArchive'.
有没有办法做到这一点,或者我做错了。谢谢。
答案 0 :(得分:2)
错误的原因是PostArchive
是您给SELECT行上的列赋予的名称,它实际上是查询的输出。 ORDER BY子句没有查看它,它查看了它对查询的输入,在本例中是PostDate
答案 1 :(得分:1)
SSSS
-- Create a CTE (inline view)
WITH T AS (
SELECT YEAR(PostDate) PostYear
, MONTH(PostDate) PostMM
, SUBSTRING(DATENAME(MONTH, PostDate),1,3) PostMonth
, COUNT(*) Posts
FROM Post
WHERE Verified = 1
GROUP BY YEAR(PostDate)
, MONTH(PostDate)
, DATENAME(MONTH, PostDate)
)
-- Build you date string
SELECT PostMonth + '-' + CAST(PostYear AS VARCHAR(4)) AS PostArchive
, Posts
FROM T
-- Sort it by the components separately
ORDER BY PostYear
-- Don't use the character, otherwise, Aug will come before Mar
, PostMM
答案 2 :(得分:0)
我使用CTE得到结果试试这个
with tempTable (PostArchiveMonth , PostArchiveYear , PostArchiveMonthName , Posts )
(
select month(PostDate) , YEAR(PostDate) , SUBSTRING(DATENAME(MONTH, PostDate), 1, 3)
COUNT(*)
FROM Post
WHERE Verified=1
group by MONTH(PostDate) ,YEAR( PostDate)
,SUBSTRING(DATENAME(MONTH, PostDate), 1, 3)
)
select PostArchiveMonthName +'-' + PostArchiveYear as PostArchive , Posts
from tempTable
order by PostArchiveYear , PostArchiveMonth
答案 3 :(得分:0)
尝试
SELECT DISTINCT
SUBSTRING(DATENAME(MONTH, PostDate), 1, 3) + '-' + CAST(YEAR(PostDate) AS VARCHAR(4)) AS PostArchive,
Posts = COUNT(*)
FROM
Post WHERE Verified=1
GROUP BY
SUBSTRING(DATENAME(MONTH, PostDate), 1, 3) + '-' + CAST(YEAR(PostDate) AS VARCHAR(4)),
YEAR(PostDate), MONTH(PostDate)
Order by Month(PostDate), Year(PostDate)
答案 4 :(得分:0)
尝试改变这一点:
ORDER BY PostArchive
......对此...
ORDER BY YEAR(PostDate)