Sql-server – Division In SQL

sql serversql-server-2008-r2t-sql

I am wanting to divide a int quantity by a number, but my output is not what I am after. This is my DDL

Create Table Orders 
(
    id int IDENTITY(1,1) PRIMARY KEY NOT NULL
    ,partid varchar(100) NOT NULL
    ,qtyordered int DEFAULT '0'
    ,orderedby varchar(100) NOT NULL
    ,ordereddate date DEFAULT GETDATE()
)

Insert Into Orders (partid, qtyordered, orderedby) VALUES
('SS100', 10, 'James'), ('RR200', 5, 'Bob'), ('NN300', 3, 'Jake'), ('OO400', 5, 'Blue')

Now I have trired using the SQL Server functions Ceiling() and Floor() but I am not getting my desired output. This is the query I tried, what do I need to do in SQL Server to get an output of 2, 2, 1?

Select
partid
,CEILING(qtyordered/3) As [First] --want to be 2
,CEILING(qtyordered/3) As [Second] --want to be 2
,FLOOR(qtyordered/3) As [Third] --want to be 1
FROM Orders
WHERE partid = 'RR200'

Best Answer

Due 'qtyordered' is an integer, you need to either, CAST/CONVERT it to decimal, or use a decimal/float value. (3.0)

Select
partid, qtyordered
,CEILING(qtyordered/3.0) As [First] --want to be 2
,CEILING(qtyordered/3.0) As [Second] --want to be 2
,FLOOR(qtyordered/3) As [Third] --want to be 1
FROM Orders
WHERE partid = 'RR200'
GO
partid | qtyordered | First | Second | Third
:----- | ---------: | :---- | :----- | ----:
RR200  |          5 | 2     | 2      |     1

dbfiddle here

According to MS DOCS, CEILING returns same type as the numeric expresion:

Return Types
Returns the same type as numeric_expression

Related Question