我有一个日期时间字段“ createdDTTM”,格式为2009-07-27 15:22:57.427
我希望仅应用日期为2019年1月1日至2019年1月31日的过滤器来提取数据。
有人可以帮忙吗?
我已经尽力了。使用各种组合进行Cast,Convert,Date,但这似乎不起作用。我烦了。请帮忙!!
我尝试了以下代码:
SELECT p.fullname,
p.dateofbirth,
po.enterprisemrn,
pro.FullName,
o.OrderName,
o.createdDTTM,
o.WherePerformed,
o.OrderNumberEXT,
a.LocationName,
a.apptnumberEXT,
OrderStatus
FROM report.AHS_Order o
JOIN report.AHS_Provider pro ON o.OrderingProviderID = pro.ID
JOIN report.AHS_Patient p ON p.ID = o.PatientID
JOIN report.AHS_Appointment a ON a.PatientID = p.ID
JOIN report.AHS_Patient_Iorg pio ON pio.personID = p.ID
JOIN report.AHS_Patient_Other po ON po.id = p.ID
WHERE p.IsInactiveFLAG = 'N'
AND p.IsDeceasedFLAG = 'N'
AND p.LastName <> 'test'
AND p.LastName <> 'allscripts'
AND o.OrderStatus = 'Active'
OR o.OrderStatus = 'Complete'
AND pio.OrganizationName LIKE '%starling%'
OR o.OrderStatus = 'In Progress'
OR o.OrderStatus = 'Need Information'
AND o.OrderType = 'L'
AND CONVERT(date, o.createdDTTM) > CONVERT(date, '20190101');
我也尝试使用Cast(),Dateadd(dd,.....),但我什么都不知道。 SQL新手。谢谢
答案 0 :(得分:1)
然后,如果o.createdDTTM是日期时间字段,则此方法应该起作用
SELECT p.fullname,
p.dateofbirth,
po.enterprisemrn,
pro.FullName,
o.OrderName,
o.createdDTTM,
o.WherePerformed,
o.OrderNumberEXT,
a.LocationName,
a.apptnumberEXT,
OrderStatus
FROM report.AHS_Order o
JOIN report.AHS_Provider pro ON o.OrderingProviderID = pro.ID
JOIN report.AHS_Patient p ON p.ID = o.PatientID
JOIN report.AHS_Appointment a ON a.PatientID = p.ID
JOIN report.AHS_Patient_Iorg pio ON pio.personID = p.ID
JOIN report.AHS_Patient_Other po ON po.id = p.ID
WHERE p.IsInactiveFLAG = 'N'
AND p.IsDeceasedFLAG = 'N'
AND p.LastName <> 'test'
AND p.LastName <> 'allscripts'
AND o.OrderStatus = 'Active'
OR o.OrderStatus = 'Complete'
AND pio.OrganizationName LIKE '%starling%'
OR o.OrderStatus = 'In Progress'
OR o.OrderStatus = 'Need Information'
AND o.OrderType = 'L'
AND (o.createdDTTM >= '2019-01-01 00:00:00' AND o.createdDTTM <='2019-01-31 23:59:59');
答案 1 :(得分:1)
该问题可能是由where子句中的OR
引起的。尝试这样的事情:
SELECT p.fullname,
p.dateofbirth,
po.enterprisemrn,
pro.FullName,
o.OrderName,
o.createdDTTM,
o.WherePerformed,
o.OrderNumberEXT,
a.LocationName,
a.apptnumberEXT,
OrderStatus
FROM report.AHS_Order o
JOIN report.AHS_Provider pro ON o.OrderingProviderID = pro.ID
JOIN report.AHS_Patient p ON p.ID = o.PatientID
JOIN report.AHS_Appointment a ON a.PatientID = p.ID
JOIN report.AHS_Patient_Iorg pio ON pio.personID = p.ID
JOIN report.AHS_Patient_Other po ON po.id = p.ID
WHERE ( p.IsInactiveFLAG = 'N'
AND p.IsDeceasedFLAG = 'N'
AND p.LastName <> 'test'
AND p.LastName <> 'allscripts'
AND o.OrderStatus = 'Active'
OR o.OrderStatus = 'Complete'
AND pio.OrganizationName LIKE '%starling%'
OR o.OrderStatus = 'In Progress'
OR o.OrderStatus = 'Need Information'
AND o.OrderType = 'L' )
AND o.createdDTTM > '20190101'
AND o.createdDTTM < '20190201'
这使用括号将日期应用于where
子句中匹配的任何其他条件。