TSQL:OR上个月的状态

时间:2017-04-14 18:25:27

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我试图找出如何只在R,D或C状态下包含PPO / PPB任务,如果在R或D中,只包括上个月完成的那些。

select 
d.Address 'Property Address',
d.Client_id 'Client ID',
t.vendor 'Vendor Name',
t.req_dt 'Date Task Ordered',
t.due_dt 'Date Task Due',
case 
when t.status = 'D' then 'Done'
when  t.status = 'C' then 'Cancel'
when   t.status = 'R' then 'Received'
else ''
End  'Task Status',
t.task_type,
d.portfolio
,am.last AssetManagerLastName
,t.done_dt TaskDoneDate
,e.submitted_dt 'Completed Date'
,DATEDIFF(day,t.req_dt,e.submitted_dt) AS [Days to Complete]
from resnet_mysql..property_details d 
 join resnet_mysql..property_tasks t on t.property_id = d.property_id
left join resnet_mysql..property_exps e on e.property_id = t.property_id and 
e.task_id = t.task_id
left join resnet_mysql.dbo.asset_mgrs AM on AM.am_id=d.am_id
where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO') 
 and 
t.status = ('C')
 OR (
  t.status IN ('R' ,'D') 
     AND
        t.done_dt = DATEADD(month, -1, GETDATE()))
order by t.vendor, t.task_type, t.req_dt desc

enter image description here

2 个答案:

答案 0 :(得分:1)

t.done_dt >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) AND t.done_dt < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0) 目前从今天开始是一个月,即3/13,这意味着你将错过其他月份的日子。如果您想要上个月的整个月,请查找上个月的第一个月和上个月的最后一个月。

<

第二个表达式查找当前月份的第一个3/31/2017 23:59:59,以确保我们获得where (d.res_id = 125 and t.task_type in( 'PPB', 'PPO')) and (t.status = ('C') OR ( t.status IN ('R' ,'D') AND t.done_dt >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) AND t.done_dt < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0) ) )

等记录
true

答案 1 :(得分:1)

在where子句中使用or条件进行过滤。注意下面的sql用于示例目的,根据需要重命名。

SELECT * 
    FROM TABLE
    WHERE task_type IN ('PPO', 'PPB')
        AND 
        ( 
            task ='C' 
                OR
            ( task IN ('R','D') AND [Date Task Ordered] BETWEEN CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
            AND CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE())) )
        )