我正在努力获得患者部门和月份的报告。我正在选择一个部门和月份。我怎样才能明智地获得所选月份记录部门。我正在尝试以下查询但不能正常工作:
SELECT MONTH(select convert(varchar,creation_Date,105) from Patient_Ref_master)
答案 0 :(得分:4)
如果您想要一个月/年对,则以下查询将起作用:
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
未在documentation中列为比较运算符。
答案 1 :(得分:-2)
select * from Patient_Ref_master
where MONTH(creation_Date)=1 --target month here, JAN as example
SQLFIDDLE
我还发现similar question您可以在此线程中获得额外的解决方法以及other answer。