我有以下表格:
TABLE_1
timestamp parameter value
---------------------------------------------------
2015-09-04 18:48:00.000 par01 1
2015-09-04 18:48:00.000 par02 2
2015-09-04 18:48:00.000 par03 3
2015-09-04 18:48:00.000 par04 4
2015-09-04 18:48:00.000 par05 5
2015-09-04 18:48:00.000 par06 6
TABLE_2
formulaID formula
---------------------------------------------------
1 (par01*par02)
2 (par03*par04)
3 (par05*par06)
我想替换table_2的公式中table_1的值。最后,执行公式。什么是最快的方式?
我知道如何使用以下代码执行公式:
DECLARE @sql VARCHAR(50)
SET @sql = '(2*2)'
EXEC('select ' + @sql)
答案 0 :(得分:1)
我过去已经这样做了,这有点棘手:
([par01]*[par02])
对此结果的一瞥将是这样的。
;WITH Table_1 AS
(
SELECT *
FROM
( VALUES
('2015-09-04 18:48:00.000', 'par01', 1),
('2015-09-04 18:48:00.000', 'par02', 2),
('2015-09-04 18:48:00.000', 'par03', 3),
('2015-09-04 18:48:00.000', 'par04', 4),
('2015-09-04 18:48:00.000', 'par05', 5),
('2015-09-04 18:48:00.000', 'par06', 6)
) Table_1([timestamp], [parameter], [value])
)
SELECT *
FROM
(
SELECT ([par01]*[par02]) as [formulaId=1], --
([par03]*[par04]) as [formulaId=2], -- This area must be dynamic
([par05]*[par06]) as [formulaId=3] --
FROM Table_1
PIVOT ( SUM(value) FOR
[parameter] in
(
[par01], [par02], [par03], -- This area must
[par04], [par05], [par06] -- be dynamic too
)
) pvt
) p
UNPIVOT
(
Value FOR FormulaId IN
(
[formulaId=1], --
[formulaId=2], -- Another dynamic area
[formulaId=3] --
)
) upvt
请注意动态区域。
答案 1 :(得分:0)
要检索某个值,您必须使用SELECT
所以你的查询可以是:
DECLARE @sql VARCHAR(500)
SET @sql = '((select value from t where parameter = ''par01'') +
(select value from t where parameter = ''par02'') +
(select value from t where parameter = ''par03'')) / 3'
EXEC('select ' + @sql)