Pergunta

I have created a calendar table that contains all the calendar dates of a year, incl. the corresponding quarter / week / month / day etc. information.

The following Select gives me a specific date, here the 17th of March. How can I extend the below to check if this falls on a Saturday or Sunday (weekDayCal = 7 or 1) and, if true, return the date for the following Monday, otherwise return the 17th ?

SELECT     *
FROM       Calendar
WHERE      (yearCal = 2014) AND (monthCal = 3) AND (dayCal = 17)

Many thanks in advance for any help with this, Mike.

Foi útil?

Solução

Assuming you have a day_of_calendar style id field, where every date is sequentially in order, then this works...

SELECT *
  FROM Calendar
 WHERE id = (SELECT id + CASE weekDayCal WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END
               FROM Calendar
              WHERE (yearCal = 2014) AND (monthCal = 3) AND (dayCal = 17)
            )

If not, then you're going to have to return to using dates in one way or another.

For example...

SELECT *
  FROM Calendar
 WHERE realDate = (SELECT realDate + CASE weekDayCal WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END
                     FROM Calendar
                    WHERE (yearCal = 2014) AND (monthCal = 3) AND (dayCal = 17)
                  )

But then you may as well just use real date calculations.

Outras dicas

I think this should work, if you do indeed have a weekDayCal column where 1=Sunday, 2 = Monday and 7 = Saturday:

SELECT     *
FROM       Calendar
WHERE      (yearCal = 2014) AND (monthCal = 3) AND (
   (dayCal = 17 and weekDayCal not in (1,7)) OR
   (dayCal = 17 + 1 and weekDayCal = 2) OR
   (dayCal = 17 + 2 and weekDayCal = 2))

This fetches rows who fall on sunaday or saturday

SELECT *
FROM Calender
WHERE DATEPART(dw, CAST( 
                        CAST(monthCal as VARCHAR(2))+ '-'+
                        CAST(dayCal as VARCHAR(2))+'-'+
                        CAST(yearCal as VARCHAR(4))

                        AS DATETIME
                        )
               ) IN(1,7)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top