Convertir valor en dos decimales

Need help to convert value of the column "Pct_To_Total" into

John,     0,36  
Sophia,   0,29  
Stella,   0,18  
Jennifer, 0,11  

Two decimal is needed only and the second decimal needed to be converted into higher value if the third decimal is bigger than value 4.

Orginal value

declare @T table  
(  
  Name varchar(50),  
  Sales decimal  
)  

insert into @T values  
('John',     '50'),  
('Sophia',   '40'),
('Stella',   '25'),  
('Jennifer', '15'), 
('Greg',     '10')  

SELECT a1.Name, a1.Sales, (a1.Sales /(SELECT SUM(Sales) FROM @T Total_Sales) ) AS Pct_To_Total
FROM @T a1, @T a2 
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) 
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

preguntado el 10 de marzo de 12 a las 12:03

4 Respuestas

SELECT round (cast(0.35714285 AS DECIMAL(10,2)),2);

esto da 0.36 your excepted result.

I tried the following query it works fine.

SELECT a1.Name, a1.Sales, round(cast((a1.Sales /(SELECT SUM(Sales) FROM @T Total_Sales)) AS DECIMAL(10,2)),2) AS Pct_To_Total
FROM @T a1, @T a2 
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) 
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;

enter image description here

respondido 10 mar '12, 13:03

Utilizan Str ()

STR(123.468, 8, 2)

Resultado

123.47

respondido 10 mar '12, 13:03

Tienes que usar round función

-> http://msdn.microsoft.com/en-us/library/ms175003.aspx

There are some options to do that ;)

respondido 10 mar '12, 13:03

SELECT ROUND(0.36, 2)   = 0.36
SELECT ROUND(0.364, 2)  = 0.36
SELECT ROUND(0.365, 2)  = 0.37

respondido 10 mar '12, 13:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.