简体   繁体   中英

T-SQL - WHERE Clause to find enters where date is next week but also in current quarter

I have a simple table structure containing tasks assigned to resources:

| TASK | START_DATE | RESOURCE | CLOSED |

| T1 | 2018-10-10 00:00:00.000 | Bill | 0 |

| T2 | 2018-11-12 00:00:00.000 | Bob | 0 |

| T3 | 2018-11-17 00:00:00.000 | Ben | 0 |

I have a report that is intended to show the tasks that need to be completed next week and my current filter is:

WHERE CLOSED = 0 AND ((DATEPART(wk,Tasks.Start_Date) -1) = DATEPART(wk,getutcdate()) and DATEPART(YY,Tasks.Start_Date) = DATEPART(yy,getutcdate()))

The filter works perfectly when the task has a start date that is in the next week but I also have tasks that run quarterly which are being excluded by this filter.

Is there a way to build a filter that includes all tasks for this quarter as well as the tasks for next week? For example the Task identified as T1 is still open despite having a start date in the past (2018-10-10 00:00:00.000) I still need it to show on my report.

Thanks!

Assuming you are using MSSQL, you can use the simplified conditions below to provide increased readability..:

WHERE CLOSED = 0 
  AND Tasks.Start_Date < DATEADD(WEEK,1,GETDATE())

EDIT: If it is required to get the tasks will start in next week and started in this quarter only, since the where clause above brings all the tasks that already started and having CLOSED=0, use below:

WHERE CLOSED = 0 
  AND Tasks.Start_Date < DATEADD(WEEK,1,GETDATE())
  AND YEAR(Tasks.Start_Date) = YEAR(GETDATE())
  AND DATEPART(QUARTER, Tasks.Start_Date)=DATEPART(QUARTER, GETDATE())

So if closed is = 0 and it is in the past? You can do an OR statement:

WHERE CLOSED = 0 
AND (
    ((DATEPART(wk,Tasks.Start_Date) -1) = DATEPART(wk,getutcdate()) and DATEPART(YY,Tasks.Start_Date) = DATEPART(yy,getutcdate()))
    OR
    Tasks.Start_Date <= GetDate()  -- if using MS SQL
)

This will return everything you already were but also where closed = 0 and the StartDate is in the past.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM