我有一张这样的表
Formular | A | B | C | ....
----------------------------------------
(A + B) | 5 | 10 | 8 | ....
(B + C) | 8 | 5 | 1 | ....
(A - Y) | 10 | 0 | 9 | ....
(A + Z) | 2 | 0 | 0 | ....
如何选择获取如下表所示的新表
Formular | A | B | C | ....| ToTal
----------------------------------------
(A + B) | 5 | 10 | 8 | ....| 15
(B + C) | 8 | 5 | 1 | ....| 6
(A - C) | 10 | 0 | 9 | ....| 1
(A + Z) | 10 | 0 | 9 | ....| ...
...
意味着它可以有很多列和非常动态的
非常感谢你!
答案 0 :(得分:1)
如果表中已有主键列,请跳过我已将row_number添加到行并使用主键列的步骤,而其余部分应相同。
CREATE TABLE Formulas (Formular VARCHAR(10), A INT , B INT , C INT)
GO
INSERT INTO Formulas VALUES
('(A + B)' , 5 , 10 , 8 ),
('(B + C)' , 8 , 5 , 1 ),
('(A - C)' , 10 , 0 , 9 ),
('(A + C)' , 10 , 0 , 9 )
GO
Select *
,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn
,0 AS Total
INTO ##Temp
FROM Formulas
ALTER TABLE ##Temp
ADD [SQL] NVARCHAR(MAX)
GO
UPDATE ##Temp
SET [SQL] = 'Select @Total = ' + Formular + ' FROM ##Temp WHERE rn = @RowNumber'
GO
Declare @Sql NVARCHAR(MAX) , @RowNumber INT, @Total INT
Declare Cur CURSOR FOR
SELECT rn , [SQL]
FROM ##Temp
OPEN Cur
FETCH NEXT FROM Cur INTO @RowNumber , @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec sp_executesql @Sql
,N'@RowNumber INT, @Total INT OUTPUT'
,@RowNumber
,@Total OUTPUT
Select @Total , @Total
UPDATE ##Temp SET Total = @Total WHERE rn = @RowNumber
FETCH NEXT FROM Cur INTO @RowNumber , @Sql
END
CLOSE Cur
DEALLOCATE Cur
Select Formular, A , B, C, Total
from ##Temp
╔══════════╦════╦════╦═══╦═══════╗
║ Formular ║ A ║ B ║ C ║ Total ║
╠══════════╬════╬════╬═══╬═══════╣
║ (A + B) ║ 5 ║ 10 ║ 8 ║ 15 ║
║ (B + C) ║ 8 ║ 5 ║ 1 ║ 6 ║
║ (A - C) ║ 10 ║ 0 ║ 9 ║ 1 ║
║ (A + C) ║ 10 ║ 0 ║ 9 ║ 19 ║
╚══════════╩════╩════╩═══╩═══════╝