Sql server 根据所选月份从表中获取月份
我正试着得到一份关于病人的报告,每月一次。我正在选择一个部门和本月的工作。如何仅获取所选月份的部门记录。我正在尝试以下查询,但不起作用:Sql server 根据所选月份从表中获取月份,sql-server,Sql Server,我正试着得到一份关于病人的报告,每月一次。我正在选择一个部门和本月的工作。如何仅获取所选月份的部门记录。我正在尝试以下查询,但不起作用: SELECT MONTH(select convert(varchar,creation_Date,105) from Patient_Ref_master) 此外,我还找到了在该线程中可以获得额外解决方法的地方。如果您想要一个月/年对,以下查询将起作用: select * from Patient_Ref_Master where Cast( '
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 )
选择*
来自患者参考大师
where Cast('20130801'作为日期)@BogdanSahlean:只有一个月的行:1968年8月或8月?请注意,如果您当前(或将来)在创建日期
列上有索引,则效率极低。一旦你有超过一年的数据,它也不会像你认为的那样工作。一个开放的范围会更好(即使被接受的答案添加了一个YEAR()
filter)。+1但是这是一种非常奇怪的方法来构造你的子句-变量@AaronBertrand-有人曾经因为看到BETWEEN
与某种日期/时间数据一起使用而大发雷霆。我发现这是一种相当清晰的方式来编写“中间”相关逻辑,尤其是在处理混合的打开/关闭间隔时。坦白地说,我不知道正确的一面是什么(1)我根本没有在
之间提出。但通常我们在左侧有一列,在右侧有一个比较器,例如创建日期>=@Start和Creation\u Date<@End
。我看不到您经常使用的表单(也不觉得它很符合逻辑),所以我问。(2) 我想你知道我说的倒排是什么意思。对列应用MONTH()意味着永远不会使用索引查找。它还假设我们想要2000年1月、2001年1月、2002年1月等等,而不是特定年份的1月。
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;