SQL 如何划分两列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3996779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 08:01:31  来源:igfitidea点击:

How to divide two columns?

sql

提问by Niko Gamulin

I tried to divide two columns from joined tables but the result (value of column relative_duration) is always 0. The query is the following:

我试图从连接的表中划分两列,但结果(列 relative_duration 的值)始终为 0。查询如下:

    SELECT t1.[user_1]
      ,t1.[user_2]
      ,t1.[total_duration]
      ,(t1.total_duration/t2.[total_events_duration]) AS relative_duration
  FROM [CDRs].[dbo].[aggregate_monthly_events] AS t1 INNER JOIN [CDRs].[dbo].[user_events_monthly_stats] AS t2 ON t1.[user_1] = t2.[user_1]

Does anyone know what could be wrong in the query above and how to fix it in order to divide column total_duration from table t1 with column total_events_duration from table t2?

有谁知道上面的查询可能有什么问题以及如何修复它以便将表 t1 中的列 total_duration 与表 t2 中的列 total_events_duration 分开?

BTW I tried to replace division with subtraction ("/" with "-") and in that case the column relative_duration is not 0.

顺便说一句,我试图用减法(“/”和“-”)替换除法,在这种情况下,relative_duration 列不是 0。

回答by AdaTheDev

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

据推测,这些列是整数列 - 这将是计算结果将具有相同类型的原因。

e.g. if you do this:

例如,如果你这样做:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

你会得到 0,这显然不是真正的答案。因此,将值转换为例如十进制并根据该数据类型进行计算。

e.g.

例如

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

给出 0.500000