문제

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 all Fridays in December. What would be the best way here to get only the second out of these ?

SELECT     *
FROM       Calendar
WHERE      (yearCal = '2014') AND (monthCal = '12') AND (weekDayCal = '6')

Many thanks in advance, Mike.

도움이 되었습니까?

해결책

Assuming that you have a day_of_month type of field, the second Friday must be day 8 to 14.

SELECT     *
FROM       Calendar
WHERE      (yearCal    = 2014)
       AND (monthCal   = 12)
       AND (weekDayCal = 6)
       AND (dayInMonth BETWEEN 8 AND 14)

You could use a Week of month field, but this can get complex depending on what you define as a week. Normally it would by Monday-Sunday or similar, meaning that week1 of month12 may only be 2 days long, and not include a Friday.

다른 팁

If this is a recurring requirement, then you should add a column weekInMonthCal and include it in the constraint clause.

It is possible to count in SQL but, as this involves aggregation in the result set, it is expensive.

You can use ROW_NUMBER() function to order your results (replace the column DateColumn with your column which stores dates. You can then get the second record.

WITH CTE AS
(SELECT     Col1, Col2, Col3, ROW_NUMBER() OVER (ORDER BY DateColumn) RowNumber
FROM       Calendar
WHERE      (yearCal = '2014') AND (monthCal = '12') AND (weekDayCal = '6'))

SELECT Col1, Col2, Col3 FROM CTE
WHERE RowNumber = 2

This would give you the second friday of a given month

SELECT TOP 1 *
FROM
(SELECT     top 2 *
FROM       Calendar
WHERE      (yearCal = '2014') AND (monthCal = '12') AND (weekDayCal = '6')
order by dateCal asc) a
order by dateCal desc
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top