TSQL查询使用计算返回值不小于1



我有一个tsql查询,用于计算百分比,如果结果> 1,则计算良好,但当结果小于1时返回0。我的计算是这样的:

create table dbo.#temptable ( 
  total_sold int null,
  #_in_ny int null,
  percent_in_ny decimal(18,2)null
) on [primary]
insert into dbo.#temptable    
    select count(t.booknum) as totalsold, t.#_in_ny, 100 * t.#_in_ny / count(t.booknum)
    from mytable t

这给了我:

total   ny sales   %sales in ny
650       4           0     ---- this should show up as 0.61 since 4 is .61% of 650

问题是SQL Server做整数除法。最简单的解决方案是使用100.0作为常量:

insert into dbo.#temptable    
    select count(t.booknum) as totalsold, t.#_in_ny,
           t.#_in_ny * 100.0 / count(t.booknum)
    from mytable t

t.#_in_ny / count(t.booknum) -你在这里做整数除法。将它们都转换为浮点数或小数。

insert into dbo.#temptable    
    select count(t.booknum) as totalsold, t.#_in_ny, 100 * CONVERT(float,t.#_in_ny) / CONVERT(float, count(t.booknum))
    from mytable t

EDIT:也可以看Gordon的回答。虽然这两种方法都有效,但他的方法肯定比我的更有说服力。

最新更新