2016-09-08 46 views
1

我有一個tsql查詢爲百分比計算,如果結果大於1,它計算得很好,但當它小於1時返回0。我的計算是這樣的:使用計算不返回小於1的計算的TSQL查詢

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 

回答

3

問題是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 
+0

在恆力sql服務器中使用float來做小數點除法嗎? –

1

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 

編輯:見戈登的回答也是如此。儘管任何一種解決方案都有效,但他肯定比我的更有說服力。

+0

你說的沒錯,你的工作很好,但戈登的簡單了。 +1雖然。謝謝。 –