2012-07-31 52 views
0

將varchar值轉換爲int時轉換失敗我無法運行以下查詢。'如果函數

我需要爲每個星期的每一天的每個模型找到多個[ID]。運行類似查詢來總結其他度量標準時,我不會遇到任何問題。

但是在這種情況下,我收到一條消息「將varchar值'07:2767:90:56'轉換爲數據類型int」時轉換失敗。

我可以在沒有(case if)函數的情況下執行對[ID]的計數查詢,而不會出現任何問題。

SELECT model, 

count(CASE WHEN datepart(weekday, [date]) =2 THEN (ID)else 0 END) AS [Monday] 
count(CASE WHEN datepart(weekday, [date]) =3 THEN (ID)else 0 END) AS [Tuesday] 
count(CASE WHEN datepart(weekday, [date]) =4 THEN (ID)else 0 END) AS [Wednesday] 
count(CASE WHEN datepart(weekday, [date]) =5 THEN (ID)else 0 END) AS [Thursday] 
count(CASE WHEN datepart(weekday, [date]) =6 THEN (ID)else 0 END) AS [Friday] 

from clientdata 

where [date] between cast ((GETDATE() -7) AS date) and cast (GETDATE()-1 AS date) 
group by d.model; 

回答

1

嘗試這個

SELECT model, 

count(CASE WHEN datepart(weekday,[date])=2 THEN ID else 0 END) AS [Monday], 
count(CASE WHEN datepart(weekday,[date])=3 THEN ID else 0 END) AS [Tuesday], 
count(CASE WHEN datepart(weekday,[date])=4 THEN ID else 0 END) AS [Wednesday], 
count(CASE WHEN datepart(weekday,[date])=5 THEN ID else 0 END) AS [Thursday], 
count(CASE WHEN datepart(weekday,[date])=6 THEN ID else 0 END) AS [Friday] 

from clientdata d 

where [date] between (GETDATE() -7) and (GETDATE()-1) 
group by d.model; 
0

我不知道爲什麼你所得到的特定錯誤,但我看到幾個問題:你的選擇(需求領域後

  • 沒有逗號一個星期一,星期二等)
  • 您正在按d.model分組,其中d不是有效的表別名
  • 您的查詢不會返回您正在查找的結果。所有這些日子都會一樣。你想用SUM,東西線沿線的:

    SUM(CASE WHEN DATEPART(平日,[日])= 2,則1,否則0 END)AS [週一]