2017-06-13 159 views
0

不相容我得到這個錯誤,雖然我試圖搜索現有答案,我無法實現在MT查詢日期與詮釋

所以我有:

消息206,級別16,狀態2,行3 操作數類型衝突:日期與詮釋

不兼容這是我的查詢:

Select emp_desc, SUM(Price*Num_Of_Products) 
from  sales 
Where sale_date between 2014-01-01 and 2017-01-01 
GRoup By emp_desc 

有什麼建議嗎? 非常感謝

+1

的可能的複製[Sql Server的操作數類型衝突:日期是不兼容INT(https://stackoverflow.com/questions/ 26019011/sql-server-operand-type-clash-date-is-incompatible-with-int) – rghome

回答

1

在你的日期文字單引號:

select 
    emp_desc 
    , sum(Price * Num_Of_Products) 
from sales 
where sale_date >= '20140101' 
    and sale_date < '20170101' 
group by emp_desc 

此外,between可能不會做你認爲這是做什麼。

參考:

唯一真正安全的格式在SQL Server中,至少datetimesmalldatetime,日期/時間文本是:YYYYMMDDYYYY-MM-DDThh:mm:ss[.nnn]
- Bad habits to kick : mis-handling date/range queries - Aaron Bertrand

+0

謝謝你們。 appriciated :-) – johndoe

+0

@johndoe快樂的幫助! – SqlZim

0

2014-01-01是int - 2014減去1減去1,或2012。如果圍繞這些表達式用單引號('),他們將成爲字符串,從字符串到日期的隱式轉換應該做的伎倆:

SELECT emp_desc, SUM(price * num_of_products) 
FROM  sales 
WHERE sale_date BETWEEN '2014-01-01' AND '2017-01-01' 
     -- Here ----------^----------^-----^----------^ 
GROUP BY emp_desc 
0

要麼你需要使用引號您所選日期

Where sale_date between '2014-01-01' and '2017-01-01' GRoup By emp_desc 

或列SALE_DATE聲明爲INT 所以你將不得不使用

Where sale_date between 20140101 and 20170101 GRoup By emp_desc 
0

以上內容由廣告肯定工程或只是丁單引號,你也可以嘗試這種方式,如果日期存儲在日期時間格式

Select emp_desc, SUM(Price*Num_Of_Products) 
from  sales 
Where convert(varchar(10),sale_date,120) between '2014-01-01' and '2017-01-01' 
GRoup By emp_desc