2014-10-10 76 views
0

我是新来编写SQL查询时遇到与在SQL中的Smalldatetime 定义的所有我需要的是月开始至月底之间tblVehicleDepreciationLine.LineDate日期时间列 tblVehicleDepreciationLine.LineDate问题.. 我读了20个不同的日期时间解决方案,但似乎无法破解我需要什么代码才能得到我的结果..SQL日期时间在一个月

任何帮助将不胜感激。

Select 
    tblVehicle.Rego, 
    tblVehicle.CompliancePlate, 
    tblVehicleType.Description, 
    tblVehicleEquipmentStatus.Description As Description1, 
    tblBranch.Name, 
    tblVehicleDepreciationLine.WDV, 
    tblVehicle.ID, 
    tblVehicleDepreciationLine.LineDate 
From 
    tblVehicle 
    Inner Join tblVehicleType On tblVehicle.VehicleType_ID = tblVehicleType.ID 
    Inner Join tblVehicleEquipmentStatus On tblVehicle.VehicleEquipmentStatus_ID = tblVehicleEquipmentStatus.ID 
    Inner Join tblBranch On tblVehicle.ControllingBranch_ID = tblBranch.ID 
    Inner Join tblVehicleDepreciationLine On tblVehicleDepreciationLine.Vehicle_ID = tblVehicle.ID 
Where 
    (tblVehicleDepreciationLine.LineDate >= 
     ('(year(getdate()), month(getdate()), 1)') And 
     tblVehicle.VehicleEquipmentStatus_ID = 1) 
Or 
    (tblVehicleDepreciationLine.LineDate < 
     ('(year(getdate()), month(getdate())+1, 1)') And 
     tblVehicle.VehicleEquipmentStatus_ID = 2) 
Order By 
    tblVehicle.ControllingBranch_ID 
+1

您使用的数据库是多少? – jpw 2014-10-10 00:52:49

回答

2

假设SQL Server。如果您想检查的日期,如果第一个和最后一个月之间,你实际上是检查它是否在同一年份和月份:

(
year(tblVehicleDepreciationLine.LineDate) = year(getdate()) 
and 
month(getdate()) = month(tblVehicleDepreciationLine.LineDate 
) 

或SQL Server,如果你想2012使用之间:

(
tblVehicleDepreciationLine.LineDate between 
datefromparts(year(getdate()), month(getdate()), 1) and eomonth(getdate()) 
) 

这可能不是最有效的方法来做到这一点,但它应该给你一个想法。

0

如果你想检查一个日期是否在相同的年份和月份,你可以使用类似WHERE tblVehicleDepreciationLine.LineDate LIKE ('2012-10%')(你可能需要修改它以适应你的服务器根据你的服务器本地将日期转换为字符串的方式)

0
--Below dates will give some idea for you 
SELECT 
'Start of Current Month' = DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0), 
'End of Current Month'  = DATEADD(ms,-10,DATEADD(m, DATEDIFF(m,0,GETDATE())+1,0)), 
'Start of Next Month'  = DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0) 


--Your WHERE clause would looks like below 
WHERE 
    (
     tblVehicleDepreciationLine.LineDate >= DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0) 
     AND tblVehicle.VehicleEquipmentStatus_ID = 1 
    ) 
    OR 
    (
     tblVehicleDepreciationLine.LineDate < DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0) 
     AND tblVehicle.VehicleEquipmentStatus_ID = 2 
    ) 
相关问题