我有一个月的数据。
DATE | AMOUNT
04/01/2019 | 3437824
04/02/2019 | 234834
04/03/2019 | 2343478
.
.
.
04/30/2019 | 343729
我想更改“日期”列以给我类似的东西
OLDDATE | DATE | AMOUNT
04/01/2019 | 01/01/2019 | 3437824
04/02/2019 | 02/01/2019 | 234834
04/03/2019 | 03/01/2019 | 2343478
.
.
.
04/12/2019 | 12/01/2019 | 328456
04/13/2019 | 01/02/2019 |845754
04/14/2019 | 02/02/2019 |845754
.
.
04/24/2019 | 12/02/2019 |845754
04/25/2019 | 01/03/2019 |845754
04/26/2019 | 02/03/2019 |845754
.
.
.
04/30/2019 | 06/03/2019 | 343729
我试图在while循环中使用开关盒来达到同样的效果,但无法获得预期的结果
BEGIN
DECLARE @Mth INT = 1;
DECLARE @Iteration INT = 1;
WHILE @Iteration != 1000000
BEGIN
WHILE @Mth <= 12
BEGIN
UPDATE TACC
SET BUSINESSDATE =
CASE
WHEN DAY([BUSINESSDATE])<13
THEN datefromparts(year([BUSINESSDATE]), @Mth, 1)
WHEN DAY([BUSINESSDATE]) BETWEEN 13 AND 24
THEN datefromparts(year([BUSINESSDATE]), @Mth, 2)
ELSE datefromparts(year([BUSINESSDATE]), @Mth, 3)
END
SET @Mth = @Mth + 1
IF @Mth=13
BEGIN
SET @Mth=1
END
END
SET @Iteration = @Iteration + 1
END
END
如果我必须要说一千万行,那将是执行T-SQL或DAX的更好方法
答案 0 :(得分:0)
基本上,我们需要将行划分为12
组,并为每个组增加新日期的月份部分。每个组中的行都需要排序,我们需要将每个新日期的日期部分增加一个。
您可以使用ROW_NUMBER
对行进行排序并将其分组。然后,您可以使用DATEADD
为每一行建立新日期:
DECLARE @DataSource TABLE
(
[DATE] DATETIME2(0)
,[AMOUNT] INT
);
INSERT INTO @DataSource ([DATE], [AMOUNT])
VALUES ('2019-04-01', 100)
,('2019-04-02', 100)
,('2019-04-03', 100)
,('2019-04-04', 100)
,('2019-04-05', 100)
,('2019-04-06', 100)
,('2019-04-07', 100)
,('2019-04-08', 100)
,('2019-04-09', 100)
,('2019-04-10', 100)
,('2019-04-11', 100)
,('2019-04-12', 100)
,('2019-04-13', 100)
,('2019-04-14', 100)
,('2019-04-15', 100)
,('2019-04-16', 100)
,('2019-04-17', 100)
,('2019-04-18', 100)
,('2019-04-19', 100)
,('2019-04-20', 100)
,('2019-04-21', 100)
,('2019-04-22', 100)
,('2019-04-23', 100)
,('2019-04-24', 100)
,('2019-04-25', 100)
,('2019-04-26', 100)
,('2019-04-27', 100)
,('2019-04-28', 100)
,('2019-04-29', 100);
DECLARE @StartDate DATETIME2 = '2019-01-01'
,@Step TINYINT = 12;
WITH DataSource ([OLDDATE], [AMOUNT], [AddMonth]) AS
(
SELECT *
,(ROW_NUMBER() OVER (ORDER BY [Date] ASC) -1 ) / 12
FROM @DataSource
)
SELECT [OLDDATE]
,[AMOUNT]
,DATEADD(DAY, ROW_NUMBER() OVER (PARTITION BY [AddMonth] ORDER BY [OLDDATE] ASC) - 1, DATEADD(MONTH, [AddMonth], @StartDate))
FROM DataSource;