2013-05-05 47 views
0

我的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'.

有沒有辦法做到這一點還是我在錯誤的way.Thanks。

+0

嘗試CAST(PostArchive爲DATETIME) – Rob 2013-05-05 11:58:24

+0

@Rob同樣的錯誤'無效列名...' – 2013-05-05 11:59:48

回答

2

的原因錯誤是PostArchive是你給對SELECT線之列,這是有效的查詢的輸出名稱。 ORDER BY子句不看那個,看起來在其輸入的查詢,在這種情況下是PostDate

+0

我不能夠使用'PostDate'在這種情況下,因爲'它是因爲它不是在聚合功能或由使用踵然後該組中的GROUP BY clause.' – 2013-05-05 12:01:59

+0

然後順序通過的東西包含無效的ORDER BY子句:'SUBSTRING(DATENAME(月,踵),1, 3)+ ' - ' + CAST(YEAR(踵)AS VARCHAR(4))'或'YEAR(踵)',或'MONTH(踵)' – 2013-05-05 12:04:02

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 
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) 
0

嘗試改變這一點:

ORDER BY PostArchive

...這個...

ORDER BY YEAR(PostDate)

1
  1. 我假設你真的不意味着要通過 年訂購,但今年不是/月。你有排序的問題是 因爲你點它作爲一個字符,而不是作爲一個日期。
  2. 你不需要DISTINCT,因爲你已經GROUP BY。
  3. 主要問題是,你已經轉換爲VARCHAR。因此, 月是不可用的。

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