我正在尝试获取患者部门和每月明智的报告。我正在选择一个部门和月份。我怎样才能明智地只获得选定月份的记录部门。我正在尝试以下查询但不工作:
SELECT MONTH(select convert(varchar,creation_Date,105) from Patient_Ref_master)
我正在尝试获取患者部门和每月明智的报告。我正在选择一个部门和月份。我怎样才能明智地只获得选定月份的记录部门。我正在尝试以下查询但不工作:
SELECT MONTH(select convert(varchar,creation_Date,105) from Patient_Ref_master)
如果您想要一个月/年对,则以下查询将起作用:
select *
from Patient_Ref_Master
where Cast( '20130801' as Date ) <= Creation_Date and Creation_Date < Cast( '20130901' as Date )
它的优点是查询可以使用索引,因为它不需要对每一行执行计算。
在查询之前计算限制通常很有帮助,例如当前月份:
declare @Start as Date = DateAdd( month, DateDiff( month, 0, GetDate() ), 0 );
declare @End as Date = DateAdd( month, 1, @Start );
select *
from Patient_Ref_Master
where @Start <= Creation_Date and Creation_Date < @End
编辑:如果将比较运算符与布尔运算符一起使用是压倒性的,我提供以下简化:
declare @Patient_Ref_Master as Table ( Id Int Identity, Creation_Date Date );
insert into @Patient_Ref_Master ( Creation_Date ) values
( '20130731' ), ( '20130801' ), ( '20130815' ), ( '20130831' ), ( '20130901' );
select * from @Patient_Ref_Master;
declare @Start as Date = DateAdd( month, DateDiff( month, 0, Cast( '20130829' as Date ) ), 0 );
declare @End as Date = DateAdd( month, 1, @Start );
-- Incomprehensible WHERE clause:
select *
from @Patient_Ref_Master
where @Start <= Creation_Date and Creation_Date < @End;
-- Simplified AB version:
with
JustRight as (
select *
from @Patient_Ref_Master
where Creation_Date in ( @Start ) ),
NotTooLate as (
select *
from @Patient_Ref_Master
where Sign( DateDiff( day, @End, Creation_Date ) ) in ( -1 ) ),
NotTooSoon as (
select *
from @Patient_Ref_Master
-- NB: Do NOT include zero in the set of matches. That would be too easy.
where Sign( DateDiff( day, Creation_Date, @Start ) ) in ( -1 ) ),
TheResult as (
select *
from JustRight
union
select *
from NotTooLate
intersect
select *
from NotTooSoon )
select * from TheResult;
不,文档IN
中未将其列为比较运算符。