正确过滤 SQL 中的日期
properly filtering Dates in SQL
我正在尝试执行我的查询,但只提取 2020 年的日期,当我添加日期部分(2020 年)时,我没有得到任何结果,尽管有 2020 年的结果。来自系统的数据格式为 YEAR-MONTH-DAY HR:MIN:SEC:SEC。谁能指导我哪里出错了?
SELECT CV3ClientVisit.ClientDisplayName, CV3ClientVisit.CurrentLocation, CV3ClientVisit.IDCode, CV3ClientVisit.VisitStatus, CV3Order.Name, CV3ClientVisit.TypeCode,
CV3User.DisplayName AS [Performed By], CV3OrderTaskOccurrence.PerformedFromDtm AS [Performed When], CV3OrderTaskOccurrence.TouchedBy AS [Cosigned By],
CV3OrderTaskOccurrence.TouchedWhen AS [Cosigned When]
FROM CV3Client INNER JOIN
CV3TaskSignature ON CV3Client.GUID = CV3TaskSignature.ClientGUID INNER JOIN
CV3ClientVisit INNER JOIN
CV3Order ON CV3ClientVisit.GUID = CV3Order.ClientVisitGUID INNER JOIN
CV3OrderTaskOccurrence ON CV3Order.GUID = CV3OrderTaskOccurrence.OrderGUID INNER JOIN
CV3TaskStatusHistory ON CV3OrderTaskOccurrence.GUID = CV3TaskStatusHistory.OrderTaskOccurrenceGUID ON CV3Client.GUID = CV3Order.ClientGUID INNER JOIN
CV3User ON CV3OrderTaskOccurrence.PerformedProviderGUID = CV3User.GUID
WHERE (CV3ClientVisit.TypeCode = 'Inpatient Admit') AND (CV3Order.Name = 'insulin lispro sliding scale injectable') AND (CV3ClientVisit.VisitStatus = 'ADM') AND
(CV3OrderTaskOccurrence.TouchedWhen = DATEPART(YEAR, 2020))
如果 touchedwhen
是一个 date/time,那么使用这样的东西:
(CV3OrderTaskOccurrence.TouchedWhen >= '2020-01-01' and
CV3OrderTaskOccurrence.TouchedWhen < '2021-01-01'
)
实际上,如果将值存储为字符串,这也有效,但我强烈建议您使用正确的数据类型存储值。
我正在尝试执行我的查询,但只提取 2020 年的日期,当我添加日期部分(2020 年)时,我没有得到任何结果,尽管有 2020 年的结果。来自系统的数据格式为 YEAR-MONTH-DAY HR:MIN:SEC:SEC。谁能指导我哪里出错了?
SELECT CV3ClientVisit.ClientDisplayName, CV3ClientVisit.CurrentLocation, CV3ClientVisit.IDCode, CV3ClientVisit.VisitStatus, CV3Order.Name, CV3ClientVisit.TypeCode,
CV3User.DisplayName AS [Performed By], CV3OrderTaskOccurrence.PerformedFromDtm AS [Performed When], CV3OrderTaskOccurrence.TouchedBy AS [Cosigned By],
CV3OrderTaskOccurrence.TouchedWhen AS [Cosigned When]
FROM CV3Client INNER JOIN
CV3TaskSignature ON CV3Client.GUID = CV3TaskSignature.ClientGUID INNER JOIN
CV3ClientVisit INNER JOIN
CV3Order ON CV3ClientVisit.GUID = CV3Order.ClientVisitGUID INNER JOIN
CV3OrderTaskOccurrence ON CV3Order.GUID = CV3OrderTaskOccurrence.OrderGUID INNER JOIN
CV3TaskStatusHistory ON CV3OrderTaskOccurrence.GUID = CV3TaskStatusHistory.OrderTaskOccurrenceGUID ON CV3Client.GUID = CV3Order.ClientGUID INNER JOIN
CV3User ON CV3OrderTaskOccurrence.PerformedProviderGUID = CV3User.GUID
WHERE (CV3ClientVisit.TypeCode = 'Inpatient Admit') AND (CV3Order.Name = 'insulin lispro sliding scale injectable') AND (CV3ClientVisit.VisitStatus = 'ADM') AND
(CV3OrderTaskOccurrence.TouchedWhen = DATEPART(YEAR, 2020))
如果 touchedwhen
是一个 date/time,那么使用这样的东西:
(CV3OrderTaskOccurrence.TouchedWhen >= '2020-01-01' and
CV3OrderTaskOccurrence.TouchedWhen < '2021-01-01'
)
实际上,如果将值存储为字符串,这也有效,但我强烈建议您使用正确的数据类型存储值。