2016-09-08 3 views
1

Ich habe eine Tsql-Abfrage, die Berechnungen für Prozentsätze, und es berechnet gut, wenn das Ergebnis> 1 ist, aber 0, wenn es kleiner als 1 ist. Meine Berechnung ist so :TSQL-Abfrage mit Berechnung nicht zurück Wert kleiner als 1

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 

Das gibt mir:

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

Antwort

3

Das Problem besteht darin, dass SQL Server eine Ganzzahldivision ausführt. Die einfachste Lösung ist 100.0 als Konstante zu verwenden:

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

tut mit einem float in der Konstante sql Server-Server, um die Dezimaldivision zu tun? –

1

t.#_in_ny/count(t.booknum) - Sie tun integer-Division hier. Konvertieren Sie beide in Floats oder Dezimalzahlen.

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: Siehe auch Gordon Antwort. Während jede Lösung funktioniert, ist sein sicherlich ein bisschen eloquenter als meins.

+0

Du hast Recht, dein arbeitete als gut, aber Gordon war einfacher. +1 für dich obwohl. Vielen Dank. –

Verwandte Themen