我正在使用SQL Server 2014
,查询中使用以下语法来计算除法结果。
USE MyDatabase
SELECT
...
CAST(cte1.[F&B] AS FLOAT) * CAST (cte1.[RN] / cte1.[Total RN] AS FLOAT) AS [F&B_Split],
CAST(cte1.[F&B] AS FLOAT) * CAST (cte1.[RN] / cte1.[Total RN] AS FLOAT) / CAST(cte1.[GN] AS FLOAT) AS [F&B_Split_PerGN]
...
FROM
table1
RN
中的列GN
和table1
是整数,列F&B
是数字类型。
这是我的结果的一部分:
RN TOTALRN GN F&B F&B_Split F&B_Split_PerGN
-------------------------------------------------------------
9 9 18 1200 1200 66.6666666666667
9 10 18 3900 0 0
当RN
和TotalRN
的值相同时(上面的行1),但是对于F&B_Split和F&B_Split_PerGN的值(上面的行2),计算似乎可以正常工作。
我在这里做什么错了?
答案 0 :(得分:0)
您关心划分的类型。我将删除演员表以浮动。但这是您的选择。
对我来说,最简单的解决方案是在除法之前乘以1.0
:
CAST(cte1.[F&B] AS FLOAT) * CAST (cte1.[RN] * 1.0 / cte1.[Total RN] AS FLOAT) AS [F&B_Split],
CAST(cte1.[F&B] AS FLOAT) * CAST (cte1.[RN] * 1.0 / cte1.[Total RN] AS FLOAT) / CAST(cte1.[GN] AS FLOAT) AS [F&B_Split_PerGN]
或者:
cte1.[F&B] * cte1.[RN] * 1.0 / cte1.[Total RN] AS [F&B_Split],
cte1.[F&B] * cte1.[RN] * 1.0 / cte1.[Total RN] AS [F&B_Split_PerGN]
如果要为表达式指定特定类型,请转换整个表达式:
convert(float, cte1.[F&B] * cte1.[RN] * 1.0 / cte1.[Total RN]) AS [F&B_Split],
convert(float, cte1.[F&B] * cte1.[RN] * 1.0 / cte1.[Total RN]) AS [F&B_Split_PerGN]