I have the following table:
Column1 Column2 Column3
04/07/2019 1
04/08/2019 2
04/09/2019 8
04/10/2019 9
04/11/2019 15
04/12/2019 16
04/13/2019 5
04/14/2019 6
04/15/2019 8
04/16/2019 9
04/17/2019 10
04/18/2019 11
04/19/2019 5
04/20/2019 5
04/21/2019 8
04/22/2019 8
04/23/2019 9
04/24/2019 10
04/25/2019 11
04/26/2019 12
04/27/2019 10
I need to find out a way to iterate through the values in column one and identify weeks which should start from Saturday - Sunday. So, in this example one iteration should be from the 14 - 20th. Or another iteration would be from the 7th through the 13th which is Saturday - Sunday. Then After identifying each week, I need to do some calculation on the other columns.The calculation would be updating Column3 if the total amount for Column2 within 1 week (Based on Column1 Saturday to Sunday) exceeds 40 or not. Then the same for the next iteration of week (Saturday - Sunday).
Desired Results:
Column1 Column2 Column3
04/07/2019 1 56
04/08/2019 2 56
04/09/2019 8 56
04/10/2019 9 56
04/11/2019 15 56
04/12/2019 16 56
04/13/2019 5 56
04/14/2019 6 54
04/15/2019 8 54
04/16/2019 9 54
04/17/2019 10 54
04/18/2019 11 54
04/19/2019 5 54
04/20/2019 5 54
04/21/2019 8 68
04/22/2019 8 68
04/23/2019 9 68
04/24/2019 10 68
04/25/2019 11 68
04/26/2019 12 68
04/27/2019 10 68
Please note: The data can range from 3 weeks to a few month. So, the code needs to capture the weeks for any specific range.
You can use datepart()
to get the week of a date. You can then use the week to partition by in a windowed sum()
. From there you can UPDATE
the table joining a derived table that gets the sum like mentioned before. To make sure the week begins on Sunday issue a SET DATEFIRST 7
before the UPDATE
.
SET DATEFIRST 7;
UPDATE t1
SET t1.column3 = t3.column3
FROM elbat t1
INNER JOIN (SELECT t2.column1,
sum(t2.column2) OVER (PARTITION BY datepart(week, t2.column1)) column3
FROM elbat t2) t3
ON t3.column1 = t1.column1;
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.