我使用下面的查询来计算表中最低正数与最低负数之间的差异:
SELECT
(
(
SELECT SUM(ID)
FROM TABLE
where ID in
(
select top 1 ID
from TABLE with (NOLOCK)
where ID > 0
)
) -
(
SELECT SUM(ID)
FROM TABLE
where ID in
(
select top 1 ID
from TABLE with (NOLOCK)
where ID < 0
order by ID desc
)
)
) As IDs_Remaining
然后我如何取IDs_Remaining
并除以另一个选择查询的结果?
答案 0 :(得分:1)
简单地与您需要的任何其他查询分开:
SELECT
(
(SELECT ... ) - (SELECT ... )
) /
(SELECT ... ) As FinalResult
请注意,如果ID是整数,则您的除法也将是整数除法(无分数)。因此,您可能需要将分母转换为浮点数据类型,然后再进行CAST((SELECT ...) AS real)
顺便说一句,从表格中选择TOP 1记录并不能确保你得到价值最低的记录。因此,当您需要最低值时,请务必添加ORDER BY ID
或ORDER BY ID ASC
(即使ID是主键,也是如此 - 除非您明确键入ORDER BY
,否则永远无法保证顺序)。
此外,如果您的ID列仅包含不同的值,则获取ID列的SUM是没有意义的。在这种情况下,您只需将查询的第一部分替换为:
SELECT (
(SELECT MIN(ID) FROM TABLE WHERE ID > 0) -
(SELECT MAX(ID) FROM TABLE WHERE ID < 0)
) as IDs_Remaining
或者,只扫描一次表:
SELECT
MIN(CASE WHEN ID > 0 THEN ID ELSE NULL END) -
MAX(CASE WHEN ID < 0 THEN ID ELSE NULL END) as IDs_Remaining
FROM TABLE
答案 1 :(得分:1)
首先像这样更改您的差异查询。
SELECT (SELECT TOP 1 ID
FROM TABLE
WHERE ID > 0 order by ID) - (SELECT TOP 1 ID
FROM TABLE
WHERE ID < 0
ORDER BY ID DESC)
然后除以另一个查询使用此。
SELECT (SELECT TOP 1 ID
FROM TABLE
WHERE ID > 0 order by ID) - (SELECT TOP 1 ID
FROM TABLE
WHERE ID < 0
ORDER BY ID DESC) /--divider select query as Result