基于其他列的计算列的公式

时间:2016-04-22 18:51:50

标签: sql-server

我有一张这样的表

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 | ....| ...

...意味着它可以有很多列和非常动态的

非常感谢你!

1 个答案:

答案 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

准备SQL语句

UPDATE ##Temp
SET [SQL] = 'Select @Total = ' + Formular + ' FROM ##Temp WHERE rn = @RowNumber'  
GO

执行SQL语句并填充保留表

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 ║
╚══════════╩════╩════╩═══╩═══════╝