SQL table with Day, Date, Month, Year, Period, Week Number? (SQL)

时间:2016-04-21 22:09:02

标签: sql sql-server alter-table getdate

I had created a table long time ago using SQL that had Day, Month, Year, Weekday, Date, and Period (example: April 2016). This is what my current table looks like:

|   Period   | Day | Month | Year | Weekday |    Date   |
|:-----------|-----|-------|------|---------|----------:|
| April 2016 | 21  | April |2016  |Thursday |2016-04-21 |

Now I am needing to add Week (it is week 1, 2,... of that current month).

This select statement gives the correct result:

SELECT datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, GETDATE()), 0)), 0), GETDATE() - 1) + 1

This query returns

4

How do I insert a new column called Week into this existing table and have it find the current week number?

I believe that the existing table is using GETDATE() to calculate its values. Unfortunately I do not have my CREATE query anymore.

Any help is much appreciated!

1 个答案:

答案 0 :(得分:0)

First add a column for week using ALTER TABLE

ALTER TABLE TableName
ADD Week int

Then UPDATE the column with the week number:

UPDATE TableName
SET Week = DATEPART(day, DATEDIFF(day, 0, [Date])/7 * 7)/7 + 1

Note: This week number is based on the day number alone, not the days of the week (Monday, Tuesday) etc.