是否有可能从select中进行选择-嵌套结果临时表而不是函数而不是过程中使用的原始表?
这很完美:
SELECT ID, PAR1, PAR2 INTO tempTABLE
FROM originalTABLE
WHERE ..CONDITIONS..
SELECT TOP 1 (tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2) AS FinalResult
FROM tempTable tbl1
INNER JOIN tempTable tbl2 on tbl2.PAR1 > tbl1.PAR1
INNER JOIN tempTable tbl3 on tbl3.PAR1 > tbl2.PAR1
ORDER BY tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2
DROP TABLE tempTable
但是由于INSERT语句,我无法在函数中使用它,所以我尝试这样:
SELECT (tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2) AS FinalResult
FROM ((SELECT ID, PAR1, PAR2 FROM originalTABLE
WHERE ..CONDITIONS.) AS tempTable) tbl1
INNER JOIN tempTable tbl2 on tbl2.PAR1 > tbl1.PAR1
INNER JOIN tempTable tbl3 on tbl3.PAR1 > tbl2.PAR1
ORDER BY tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2
但是失败了。
答案 0 :(得分:0)
这应该可以正常工作:
SELECT (tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2) AS FinalResult
FROM (SELECT ID, PAR1, PAR2 FROM originalTABLE
WHERE ..CONDITIONS.
) AS tempTable tbl1 JOIN
tempTable tbl2
ON tbl2.PAR1 > tbl1.PAR1 JOIN
tempTable tbl3
ON tbl3.PAR1 > tbl2.PAR1
ORDER BY tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2;
子查询仅使用一组括号。
请注意,您也可以使用:
ORDER BY FinalResult
在ORDER BY
子句中可以识别列别名。
答案 1 :(得分:0)
您可以直接用CTE替换时态表:
with tempTable as (
SELECT ID, PAR1, PAR2 INTO tempTABLE
FROM originalTABLE
WHERE ..CONDITIONS..
)
SELECT TOP 1 (tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2) AS FinalResult
FROM tempTable tbl1
INNER JOIN tempTable tbl2 on tbl2.PAR1 > tbl1.PAR1
INNER JOIN tempTable tbl3 on tbl3.PAR1 > tbl2.PAR1
ORDER BY tbl1.PAR2 + tbl2.PAR2 + tbl3.PAR2