Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hell All

How do I use SQL to find out a couple of things?

Here's my basic table
Date    	Tom
09-Mar-14	1
10-Mar-14	1
11-Mar-14	1
12-Mar-14	0
13-Mar-14	0
14-Mar-14	1
15-Mar-14	0
16-Mar-14	1
17-Mar-14	1
18-Mar-14	1
19-Mar-14	0
20-Mar-14	1
21-Mar-14	1
22-Mar-14	1
23-Mar-14	0
24-Mar-14	1
25-Mar-14	
26-Mar-14	
27-Mar-14	
28-Mar-14	
29-Mar-14	
30-Mar-14	
31-Mar-14	
01-Apr-14	
02-Apr-14	
03-Apr-14	
04-Apr-14	
05-Apr-14	


We have GETDATE() returning todays date 24-Mar-14.
1 represents a work day
0 represents an off day

Right now I have two questions.

1. Is there a way using GETDATE() and count the number of days off, so counting the 0's backwards as a variable. Let's use 4 days. So that it counts 4 zeros from GETDATE() which would return 13-Mar-14.

2. Then I want to use another variable of adding 10 working days whether worked or not from the GETDATE() - 4(0s) (13-Mar-14). So from 13-Mar-14 adding 10 days into the future of actually worked days and potential working days would be 26-Mar-14. There must also be a way to use specific dates instead of always using GETDATE().

I know it's a bit of an odd thing but I'm doing some auditing on time worked and future potential working days. The funny thing is that there are so many rules to working days that I'm hoping that if I can figure this out with some help I'll be able to modify it to figure other problems.

Anyways, any help would be much appreciated.

Thanks

Mike
Posted

1 solution

This is for question 1, use single CTE:
SQL
WITH CTE1 (row, date, tom)
AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY date DESC) AS row,
        date, tom FROM table1 WHERE tom = 0 AND date < '24-Mar-2014'
)
SELECT date FROM CTE1 WHERE row = 4


and question 2, need multiple CTEs:
SQL
WITH CTE0 (row, date, tom)
AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY date DESC) AS row,
        date, tom FROM table1 WHERE tom = 0 AND date < '24-Mar-14'
),
CTE1 (date, tom)
AS
(
    SELECT date, tom FROM table1 WHERE tom = 1 OR tom IS NULL
),
CTE2 (var)
AS
(
     SELECT TOP 10 CTE1.date FROM CTE1 WHERE
      CTE1.date > (SELECT date FROM CTE0 WHERE row = 4)  ORDER BY date ASC
) SELECT MAX(var) FROM CTE2
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900