How do I get an int - sql

Seems like a simple question... but I am stumped.
declare #Total_User int
set #Total_User = 8
declare #Total int
set #Total = 12
declare #Number int
set #Number = (#Total_User / #Total) * 100
select #Number as 'Standard'
I am expecting 66, but my select comes out zero ??
What am I doing wrong?

The result of (#Total_User / #Total) is zero, as it is doing integer division.
You can multiply by 100 first, which gives the result that you expected:
set #Number = 100 * #Total_User / #Total
To get a rounded value rather than truncated, you would use floating point values and the round function:
set #Number = round(100.0 * #Total_User / #Total, 0)
This will give the result 67 rather than 66, as that is closer to the actual result 66.6666666666

Try:
set #Number = (#Total_User*100 / #Total)

Your division #Total_User / #Total is using integer arithmetic i.e. any remainder will be discarded, so that part of the expression will be 0.
To fix, write (1.0 * #Total_User / #Total) * 100. This promotes the operation to floating point.

You are doing integer arithmetic, that is why you see the 0, make at least one of the operand as float and you will see the correct result like:
declare #Total float
Or you can cast one operand as float like:
et #Number = (CAST(#Total_User as float) / #Total) * 100
Your current code is doing:
8 / 12
Which would result in 0.666666666667, but since both of your operands are of type int the calculation is performed using int type, thus result in 0 and not 0.66666666667.

You get 0 because you are doing integer division of #Total_User and #Total.
You have two options to get the correct result:
First multiply Ttotal_User by 100 and then divide by #Total:
set #Number = (#Total_User * 100) / #Total
Cast #Total_User and #Total to floating point before making the division:
set #Number = (cast(#Total_User as float) / cast(#Total as float)) * 100

declare #Total_User float,
#Total float,
#Number float
SET #Total_User = 8
SET #Total = 12
SET #Number = #Total_User / #Total * 100
select CAST(#Number AS INT) AS 'Standard'
This will give you 66

Related

Calculation using SQL server

Formula used
This is the formula that I used to calculate
Expressed as a single equation:
eGFR = 142 x min(Scr/κ, 1)α x max(Scr/κ, 1)-1.200 x 0.9938Age x 1.012 [if female]
where:
Scr = serum creatinine in mg/dL
κ = 0.7
α = -0.329
min(Scr/κ, 1) is the minimum of Scr/κ or 1.0
max(Scr/κ, 1) is the maximum of Scr/κ or 1.0
Age (years)
Code that I tried
select
ROUND(141 * power(min(cast(40 as float) / 0.7 ) ,-0.329) *
power(max( cast(40 as float) / 0.7 * 1) ,- 1.209) * 0.993 *
cast(42 as float) * 1.018 ,2) as kidney
Correct answer should be 123.
Any clue what I am missing in the query?
Don't use MIN and MAX, those are aggregate (GROUP BY) functions. It would be good if SQL Server had GREATEST and LEAST functions, but it doesn't yet.
IIF(a < b, a, b) is LEAST(a,b).
IIF(a > b, a, b) is GREATEST(a,b).
Don't sweat the CASTs.
Make no assumptions about operator precedence ( x before +, etc). Use parentheses.
Here's a rewrite of what I believe your formula should be. But I'm not getting the right answer yet either.
DECLARE #Scr AS INT = 40;
DECLARE #k AS FLOAT = 0.7;
DECLARE #a AS FLOAT = -0.329;
DECLARE #age AS INT = 42;
DECLARE #gender AS VARCHAR(MAX) = 'female';
DECLARE #factor AS FLOAT = CASE WHEN #gender = 'male' THEN 1.0 ELSE 1.012 END;
SELECT 142
+ (IIF(1 < #Scr/#k, 1, #Scr/#k) * #a)
* (IIF(1 > #Scr/#k, 1, #Scr/#k))
- (1.2 * 0.993 * #age * #factor);
I obviously misunderstood your formula, but this should get you started. Here's a fiddle.
According to this site your equation is kinda wrong. Please be sure to add ^ to display the "to the power of".
DECLARE #Scr AS FLOAT = 40.0;
DECLARE #gender AS VARCHAR(10) = 'female';
DECLARE #age AS SMALLINT = 42;
DECLARE #k AS FLOAT = CASE WHEN #gender = 'male' THEN 0.9 ELSE 0.7 END;
DECLARE #a AS FLOAT = CASE WHEN #gender = 'male' THEN -0.302 ELSE -0.241 END;
DECLARE #factor AS FLOAT = CASE WHEN #gender = 'male' THEN 1.000 ELSE 1.012 END;
SELECT 142 * POWER(IIF(1 < (#Scr/#k), 1, #Scr/#k), #a)
* POWER(IIF(1 > (#Scr/#k), 1, #Scr/#k), -1.200)
* POWER(0.9938, #age)
* #factor;
Also this result is correct since it is calculated in mg/dl and your expected value is in umol/l
Here is another website (it may be german, but it should do the trick)

NPER excel function in SQL

Has anybody figured out how to use NPER excel function to SQL? Use case is that I am trying to find the remaining terms of an acct in SQL.
Fields:
Current_principalbalance - PV
Current_interestrate/100/12 - RATE
Current_paymentamount- PMT
No types in data
no FV in data
I tried:
Use NLS
go
declare #fv float
declare #rate float
declare #Pmt float
declare #k float
declare #pv float
set #fv=0
set #rate=(select (current_interest_rate/100/12) from loanacct)
set #pmt= (select amortized_payment_amount from loanacct_payment)
set #pv = (select current_principal_balance from loanacct)
set #k=1
select Log10((-#Fv * (#Rate / #k) + #Pmt)
/ (#Pmt + (#Rate / #k) * #Pv))
/ Log10(1 + #Rate) as nper
from loanacct a, loanacct_detail b, loanacct_setup c, loan_class d, loan_group e, loanacct_payment f
where a.acctrefno = b.acctrefno
and b.acctrefno = c.acctrefno
and a.loan_class2_no = d.codenum
and e.loan_group_no = a.loan_group_no
and f.acctrefno = a.acctrefno
and e.loan_group_no = 55
and a.loan_number IN (66515,67214,65980)
but now i get the error: Msg 512, Level 16, State 1, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Since NPER is a forumla it would be possible to implement it in SQL since the operators for a formula would almost always be supported in databases
When using "Log" in your query, the natural logarithm is considered, and nper uses the Log to base 10. Therefore the formula should be altered as
select Log10((-#Fv * (#Rate / #k) + #Pmt)
/ (#Pmt + (#Rate / #k) * #Pv))
/ Log10(1 + #Rate) as nper
Here is a test case which compares the value from excel nper function and one from the sql server database, that matches using your example..
--I have edited the datatypes to be float
declare #fv float
declare #rate float
declare #Pmt float
declare #k float
declare #pv float
set #fv=0
set #rate=15.99/100/12
set #pmt=-167.65
set #pv =1491.42
set #k=1
--In case the interests obtained at start of period then set #k as follows
--set #k = 1 + #rate
select Log10((-#Fv * (#Rate / #k) + #Pmt)
/ (#Pmt + (#Rate / #k) * #Pv))
/ Log10(1 + #Rate) as nper
+------------------+
| nper |
+------------------+
| 9.53201056406188 |
+------------------+
Excel
=NPER(15.99/100/12, -167.65,1491.42,0)
Here is a dbfiddle link
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=2f470cee443e10647f83d6e640129d51
For this use case this was my solution and it works perfect to NPER function in excel:
declare #fv float
declare #k float
set #fv=0
set #k=1
select CEILING(Log10((-#Fv * ((current_interest_rate/100/12) / #k) + -amortized_payment_amount)
/ (-amortized_payment_amount + ((current_interest_rate/100/12) / #k) * current_principal_balance))
/ Log10(1 + (current_interest_rate/100/12))) as nper

How to round of 0.5 in sql-server?

How to round of 0.5 in sql-server?
Sample input : 16.65
Try this
DECLARE #val DECIMAL(8,2) = 16.65
SELECT CAST(CEILING((#val)*2)/2 AS DECIMAL(8,1))
output: 17.0
DECLARE #val DECIMAL(8,2) = 16.07
SELECT CAST(CEILING((#val)*2)/2 AS DECIMAL(8,1))
output: 16.5
You have to add 0.5 to Your number and use FLOOR function on that added sum.
For Example:
declare #number decimal(4,2)
set #number = 16.65
select FLOOR(#number + 0.5)
I tried below query.
DECLARE #Val FLOAT;SET #Val = 16.65
SELECT
CASE
WHEN (ROUND(#Val / 10,1) * 10)>#Val
THEN ROUND(#Val / 10,1) * 10
ELSE (ROUND(#Val / 10,1) * 10) + 0.5
END

How to Return Resultset with a Given Radius

I have the following SQL (SQL Server) and it works for the most part. The problem is I am really creating a square and not a true circle. My goal is to pass in a city and state which has a lat and long, then find all cities within a 100 mile radius of that lat long. The latitude and longitude are stored in the DB so all my values are there. I just need a more precise way of doing it. Here is my code thus far:
ALTER PROCEDURE [dbo].[sp_StoresByZipArea] (#zip nvarchar(5), #Radius float) AS
DECLARE #LatRange float
DECLARE #LongRange float
DECLARE #LowLatitude float
DECLARE #HighLatitude float
DECLARE #LowLongitude float
DECLARE #HighLongitude float
DECLARE #istartlat float
DECLARE #istartlong float
SELECT #iStartlat=Latitude, #iStartLong=Longitude from zipcodes where zipcode=#ZIP
SELECT #LatRange = #Radius / ((6076 / 5280) * 60)
SELECT #LongRange = #Radius / (((cos((#iStartLat * 3.141592653589 / 180)) * 6076.) / 5280.) * 60)
SELECT #LowLatitude = #istartlat - #LatRange
SELECT #HighLatitude = #istartlat + #LatRange
SELECT #LowLongitude = #istartlong - #LongRange
SELECT #HighLongitude = #istartlong + #LongRange
/** Now you can create a SQL statement which limits the recordset of cities in this manner: **/
SELECT * FROM ZipCodes
WHERE (Latitude <= #HighLatitude) AND (Latitude >= #LowLatitude) AND (Longitude >= #LowLongitude) AND (Longitude <= #HighLongitude)
I've used the great circle distance to do this in the past. The implementation below tells you the distance between two different points, which could be used to do what you are talking about:
create function dbo.GreatCircleDistance
(
#Latitude1 float,
#Longitude1 float,
#Latitude2 float,
#Longitude2 float
)
returns float
as
/*
FUNCTION: dbo.GreatCircleDistance
Computes the Great Circle distance in kilometers
between two points on the Earth using the
Haversine formula distance calculation.
Input Parameters:
#Longitude1 - Longitude in degrees of point 1
#Latitude1 - Latitude in degrees of point 1
#Longitude2 - Longitude in degrees of point 2
#Latitude2 - Latitude in degrees of point 2
*/
begin
declare #radius float
declare #lon1 float
declare #lon2 float
declare #lat1 float
declare #lat2 float
declare #a float
declare #distance float
-- Sets average radius of Earth in Kilometers
set #radius = 6371.0E
-- Convert degrees to radians
set #lon1 = radians( #Longitude1 )
set #lon2 = radians( #Longitude2 )
set #lat1 = radians( #Latitude1 )
set #lat2 = radians( #Latitude2 )
set #a = sqrt(square(sin((#lat2-#lat1)/2.0E)) +
(cos(#lat1) * cos(#lat2) * square(sin((#lon2-#lon1)/2.0E))) )
set #distance =
#radius * ( 2.0E *asin(case when 1.0E < #a then 1.0E else #a end ))
return #distance
end
Not sure if this helps, but I think there is an error here:
SELECT #LatRange = #Radius / ((6076 / 5280) * 60)
The (6076 / 5280) part will always evaluate to 1.
This functionality is available in-box for SQL Server 2012 and above. See Query Spatial Data for Nearest Neighbor:
DECLARE #g geography;
DECLARE #h geography;
-- SRID 4326 specifies the use of WGS 84 coordinate system (same as GPS)
SET #g = geography::STGeomFromText('POINT(-122.360 47.656)', 4326);
SET #h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
-- Returns 995 meters
SELECT #g.STDistance(#h);

Microsoft SQL rounding off to whole number, need to 1 decimal place [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Truncate (not round) decimal places in SQL Server
Can't figure this out. I need 1 decimal place returned while SQL is rounding to whole numbers.
I read that integers divided by integers give integers in SQL, but I need the one truncated decimal place for value of output in the temp table.
I don't mind if 35.0 comes back as 35 but 35.17 should come back as 35.1. Sorry just edited. Need to truncate the last number, not round up.
create table #blah(output decimal(9,1))
DECLARE #a money
DECLARE #b money
DECLARE #intinterval decimal(9,1)
SET #a = 5
SET #b = 2
SET #intinterval = (#b / 1000.0) * (86400.0 / #a)
INSERT INTO #blah (output) VALUES (#intinterval)
SELECT * from #blah
drop table #blah
The above equation should give (2 / 1000) * (86400 / 5) = (0.002 * 17280) = 34.56
The 34.56 should truncate to 34.5
SET #intinterval = cast(10 * (#b / 1000.0) * (86400.0 / #a) as int) / 10.0
or
SET #intinterval = cast(#b * 864.0 / #a as int) / 10.0
What about Round((#b / 1000.0) * (86400.0 / #a), 1, 1), where last 1 saying to truncate instead of round.
try this with no special functions...
if
a = 5 then output = 34.5 (34.56)
a = 7 output = 24.6 (24.69)
a = 11 output = 15.7 (15.71)
create table #blah(output decimal(9,1))
DECLARE #a money
DECLARE #b money
DECLARE #intinterval decimal(9,2)
declare #rounded decimal(9,1)
declare #diff decimal(9,2)
declare #finalvalue decimal(9,1)
SET #a = 5
SET #b = 2
SET #intinterval = (#b / 1000.0) * (86400.0 / #a)
set #rounded = #intinterval -- gets the rounded value
set #diff = #intinterval - #rounded -- gets the difference whether to round off or not
if #diff >= 0 -- if differnce is >= 0 then get the rounded value .. eg. 34.31 = 34.3
set #finalvalue = #rounded
else -- else subtract 0.1 and get the rounded value e.g. 34.56 - 0.1 = 34.46 -> rounded value of 34.5
set #finalvalue = #intinterval - 0.1
INSERT INTO #blah (output) VALUES (#finalvalue )
SELECT * from #blah
drop table #blah