2016-01-13 100 views
0

我正在使用C#,嘗試按月排序數據。我有一個日期列StartDate和查詢如下:字符串到日期時間錯誤

SELECT 
    CompanyKey, CompanyName, CAST(Month(StartDate) as varchar(2)) + '/' + 
    CAST(YEAR(StartDate) as varchar(4)) as StartDate, SUM(Visits) 

    FROM ProfileStats    
    WHERE StartDate between '2012/12/28' and '2015/12/29' 
    GROUP BY CompanyKey, CompanyName, StartDate, Visits 

但是,如果使用一個月(StartDate)或CAST語法,它拋出一個異常:

Additional information: Object of type 'System.String' cannot be converted 
to type 'System.DateTime'. 

任何幫助/線索將不勝感激。

+0

您的日期時間轉換爲varchar在SQL,爲什麼呢? – Seano666

+0

你想要什麼日期顯示?是MM/yyyy嗎? – abramlimpin

+0

如果你真的想這樣做,你錯過了日期的一部分......但是你不必像C#自動執行日期或日期時間列。 –

回答

1

StartDate是一個DateTime列,您試圖將其創建爲一個字符串。您需要創建一個DateTime對象,可能如Create a date with T-SQL中所示,儘管不知道您使用的是哪種SQL變體,但很難回答。

如果你按月試圖組我柯克布羅德赫斯特的答案達成一致,通過使組,利用一個月修改:

SELECT CompanyKey, CompanyName, StartDate, SUM(Visits) 
FROM ProfileStats  
WHERE StartDate between '2012/12/28' and '2015/12/29' 
GROUP BY CompanyKey, CompanyName, YEAR(StartDate), MONTH(StartDate), Visits 

,只是如果你想按月排序你需要一個排序詞組,不是嗎?例如:

SELECT CompanyKey, CompanyName, YEAR(StartDate) + '-' + MONTH(StartDate) AS StartDate_YearMonth, SUM(Visits) 
FROM ProfileStats  
WHERE StartDate between '2012/12/28' and '2015/12/29' 
GROUP BY CompanyKey, CompanyName, YEAR(StartDate) + '-' + MONTH(StartDate), Visits 
ORDER BY CompanyKey, CompanyName, YEAR(StartDate) + '-' + MONTH(StartDate), Visits 

除非您想按其他屬性進行分組並按月分類而不使用這些組。你有點模糊

+0

感謝編輯Alex。這對我來說很懶。 – christutty

0

你的C#代碼試圖將你返回的字符串(VARCHAR)轉換爲DateTime對象。如果格式正確,它可以這樣做,但是這種格式不正確 - 僅僅是月份和年份。請選擇StartDate

SELECT CompanyKey, CompanyName, StartDate, SUM(Visits)  
FROM ProfileStats   
WHERE StartDate between '2012/12/28' and '2015/12/29' 
GROUP BY CompanyKey, CompanyName, StartDate, Visits 

它將被裝入一個C#DateTime對象,然後你可以使用.Month屬性做任何分組或過濾。

如果您想選擇開始在每個月的開始部分合成日期,允許分組,我能想到的兩個SQL選擇:

  • 選擇日期與01每天值,例如

    CAST(YEAR(StartDate) as varchar(4)) + '-' + CAST(Month(StartDate) as varchar(2)) + '-01' + as StartDate

  • 減去從SQL日期目前的 '天';例如1/13減去(13-1)得到1/1;爲1/15減去(15-14)得到1/1。

    StartDate - (DAY(StartDate) - 1)


不過,如果你需要做你的應用程序分組和過濾,我可能更喜歡帶回整個日期和執行應用程序中的過濾。

+0

謝謝柯克,但我已經嘗試過這種解決方案,我試圖通過使用月(StartDate)和年(StartDate)作爲月/月提取數據「月」 使用StartDate將根據DD/MM/YYYY。 – ashhad

+0

您無法創建僅有月份和年份的日期。你可以創建一個類似於'YYYY-MM-01'的字符串,C#應該始終接受這個字符串(注意,年份 - 月 - 日是日期的最佳字符串表示,因爲它在文化上是明確的)。然而,從一個日期到一個字符串,並不是理想的模式,我會親自避免它。 –

+0

非常感謝Kirk,我得到了你的解釋。它講得很有道理。我只是想辦法實現這一點。也許可以通過使用多個if/else或使用Linq來實現。 – ashhad

0

假設你正在努力實現mm/yyyy格式爲您STARTDATE 你可以使用這樣的事情

SELECT 
CompanyKey, CompanyName, , SUM(Visits) ,right( CONVERT(VARCHAR(10),startdate,103),7) as startdate ,SUM(Visits) 

FROM ProfileStats    
WHERE StartDate between '2012/12/28' and '2015/12/29' 
GROUP BY CompanyKey, CompanyName, StartDate, Visits