我不能爲我的生活得到這個工作。我已經嘗試了我在這裏和遍佈互聯網上看到的每一個例子。我試圖根據一個月的數據進行查詢。在我查詢視圖中的數據的格式如下:SQL Server:查詢條件 - 需要從日期時間提取日期
2012-03-20 00:00:00.000
使用下列標準這勾起所有的日期(或幾乎所有的)。有任何想法嗎?
AND cast(convert(varchar(10), lag.postingdate, 112) as datetime) between '2015-01-01' and '2015-01-31'
原始查詢:
SELECT
prov.pgrp_id AS PERFORMING_PROV_ID
, prov.pgrp_prov_name AS PERFORMING_PROV_NAME
, lag.chgno AS CHARGE_NUM
, lag/countcharges AS LAGTIME
, lag.chgamt
, lag.postingdate
FROM
dbo.Providers prov
RIGHT JOIN
dbo.LagTime_Charges_Calcs lag ON prov.pgrp_prov_cd = lag.provcode
AND prov.pgrp_practice = lag.px
LEFT JOIN
dbo.PlaceofService_union_v pos ON lag.px = pos.px
AND lag.poscode = pos.poscode
WHERE
pos.posid = '1'
OR pos.posid = '2'
AND prov.Laginclude = 'y'
AND MONTH(lag.postingdate) = 1
AND YEAR(lag.postingdate) = 2015
--and lag.postingdate between '2015-01-01 00:00:00.000' and '2015-01-31 23:59:59.000'
--AND cast(convert(varchar(10),lag.postingdate,112) as datetime) between '2015- 01-01' and '2015-01-31'
你爲什麼要轉換爲字符串?試試'WHERE lag.postingdate> ='20150101'AND lag.postingdate <'20150201';'。請閱讀[本文](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/16/bad-habits-to-kick-mishandling-date-range-queries.aspx)和[本文] (http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have-in-common.aspx)。 – 2015-02-10 20:51:08
另外,停止談論「格式」 - 什麼是實際的*數據類型*?該視圖是否呈現該輸出,因爲它出於某種原因將日期/時間值格式化爲字符串?如果是這樣,停止這樣做... – 2015-02-10 20:58:01
上面的例子不適合我。此列的數據類型是(datetime,null) – gfuller40 2015-02-10 21:02:25