【问题标题】:How to get CAST working correctly with division如何让 CAST 与除法一起正常工作
【发布时间】:2017-05-25 14:41:01
【问题描述】:

我正在使用 SSMS 2014。

我的示例代码如下:

select name
      ,family
      ,group
      ,mcount
      ,icount
      ,(cast(icount as demical(10,2)) / cast(mcount as decimal(10,2))) as per_unit 
from ( select distinct 
           mc.name
          ,mc.family
          ,mc.group
          ,sum(mc.mcount) over (partition by mc.name) as mcount
          ,sum(ic.icount) over (partition by ic.name) as icount
      from mc
      join ic
         on ic.num1 = mc.num1) as a
order by mcount desc

我的每单位列的第一条记录应该除以 76 / 50。这应该 = 1.52,但是,它返回 1.5200000000000。第二条记录除以 52/28 并返回 1.8571428571428。

我正在寻找 2 位小数。我读到强制转换为十进制(10,2),但这似乎不起作用。

我做错了什么?? 谢谢

【问题讨论】:

  • demical 拼写错误...
  • 当您将 76 和 50 分开时 - 它们都没有小数位。但结果有。为什么您认为结果将具有与参数相同数量的小数?
  • 你知道...我问是因为我不知道。我想在这里保持礼貌。但如果你要问我这个问题,我显然没有答案……因为我问的是上述问题。不要发布任何东西。如果您像下面试图提供帮助的人一样有什么可以贡献的,请务必去做...否则...不要发帖,因为您没有帮助任何人。

标签: sql tsql ssms window-functions


【解决方案1】:

你必须转换除法的结果。

改变这个

(cast(icount as demical(10,2)) / cast(mcount as decimal(10,2))) as per_unit

到这里

cast(icount  / mcount  as decimal(10,2)) as per_unit 

如果 icount 和 mcount 是 int ,则保留现有的演员表。

【讨论】:

  • 感谢您的回答——这给了我 1.00 和 2.00 而不是 1.52,但它走上了正确的道路——我想我可以用它来做其他事情!!所以这绝对是有帮助的 - 我也没有指出列格式......我应该这样做!谢谢你的帮助!
【解决方案2】:

将您的部门更改为:

cast((cast(icount as demical(10,2)) / cast(mcount as decimal(10,2))) as decimal(10,2)) as per_unit 

或者理想情况下,假设您的 icount 和 mcount 也是 decimal 值:

cast(icount / mcount as decimal(10,2)) as per_unit

【讨论】:

  • 谢谢!这非常有效!我有不到 15 个代表,所以我不能投票。但这正是我所需要的(最上面的例子)。
  • @RyanOtto 如果这是您问题的正确答案,为了其他 SO 用户的利益,请接受它作为答案。这与投票不同。
【解决方案3】:

再投一次就会得到想要的结果

 cast((cast(icount as demical(10,2)) / cast(mcount as decimal(10,2))) as Decimal(10,2)) per_unit 

【讨论】:

  • 感谢您的帮助!这也类似于上面的最佳答案,并且效果很好!!!再说一次,因为我有不到 15 个代表,我不能投票,但这正是我需要的!!!
猜你喜欢
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 2017-02-27
  • 2021-12-27
  • 2012-07-02
  • 1970-01-01
相关资源
最近更新 更多