SQL Query returning 0 when there is data - sql

I have the following SQL Query:
SELECT
a.IA
, a.PC
, a.LC
, a.CXPevalCnt
, ((a.IA / nullif(a.CXPevalCnt,0))*0.35) as IAcalc
, ((a.LC / nullif(a.CXPevalCnt,0))*0.5) as legacalc
, ((a.PC / nullif(a.CXPevalCnt,0))*0.15) as pccalc
, (
((a.IA / nullif(a.CXPevalCnt,0))*0.35)
+ ((a.LC / nullif(a.CXPevalCnt,0))*0.5)
+ ((a.PC / nullif(a.CXPevalCnt,0))*0.15)
) as Compliance
FROM
(
SELECT
SUM(IA) as IA
, SUM(PC) as PC
, SUM(LC) as LC
, SUM(CXPevalcount) as CXPevalCnt
FROM
tblPLOps_Data
) as A
Which returns the following data:
IA PC LC CXPevalCnt IAcalc legacalc pccalc Compliance
15 12 15 15 0.35 0.5 0 0.85
If PC is 12 and CXPevlacnt is 15 I cannot figure out why in my query when I add them together cxpevalcount nulls out but only for PC and not when used with IA or LC. I have sliced this query many different ways and can't figure out the issue
any ideas?

Because you are doing integer division. 12/15 = 0. If you want to do accurate math you need to multiply one of them by 1.0 or convert to force sql to do numeric division.
((a.PC * 1.0) / nullif(a.CXPevalCnt, 0)) * 0.15 as pccalc
You would need to do the same for your other columns as well.

Related

How can I Roundoff in SQL with a sum function

In My SQL Code I am trying to round the value to 2 decimal point with sum
select ((SUM(Round((CAST(PE.GstTotal as float) * PE.Quantity) / 2 ),2))) FROM [dbo].[PharmacyEntry] PE
But I am getting an error. Could someone correct me on this.
Error
It's sometimes helpful to vertically align all your parenthesis pairs to see where you've got one wrong:
select
(
(
SUM
(
Round
(
(
CAST
(
PE.GstTotal as float
)
*
PE.Quantity
)
/
2
),
2
)
)
)
FROM [dbo].[PharmacyEntry] PE
You're providing 2 as a second parameter to sum instead of round. Try this:
select SUM(Round((CAST(PE.GstTotal as float) * PE.Quantity) / 2 , 2))
FROM [dbo].[PharmacyEntry] PE

Why does Postgres select return wrong floating point calculation?

Why does SELECT 2 * 4 * ( 5 / 2) * 4 return 64 instead of 80?
The real query I'm running looks like this:
SELECT 2 * equity_gains_score * (tenure_score / 2) * investor_score AS propensity
but I had the same result when I ran it substituting numbers for columns. How can I fix this statement?
Postgres does integer division. So, 5/2 is 2 rather than 2.5.
You can just add a decimal point to one of the operands of the division:
SELECT 2 * 4 * ( 5 / 2.0) * 4
Or convert a value to a numeric:
SELECT 2 * 4 * ( 5::numeric / 2.0) * 4
Note: If you want an integer as the result, then you need to convert back to an integer:
SELECT (2 * 4 * ( 5 / 2.0) * 4)::int

Get column sum and use to calculate percent of total, why doesn't work with CTEs

I did this following query, however it gave the the result of 0 for each orderStatusName, does anyone know where is the problem?
with tbl as (
select s.orderstatusName, c.orderStatusId,count(c.orderId) counts
from [dbo].[ci_orders] c left join
[dbo].[ci_orderStatus] s
on s.orderStatusId = c.orderStatusId
where orderedDate between '2018-10-01' and '2018-10-29'
group by orderStatusName, c.orderStatusId
)
select orderstatusName, counts/(select sum(counts) from tbl as PofTotal) from tbl
the result is :0
You're using what is known as integer math. When using 2 integers in SQL (Server) the return value is an integer as well. For example, 2 + 2 = 4, 5 * 5 = 25. The same applies to division 8 / 10 = 0. That's because 0.8 isn't an integer, but the return value will be one (so the decimal points are lost).
The common way to change this behaviour is to multiply one of the expressions by 1.0. For example:
counts/(select sum(counts) * 1.0 from tbl) as PofTotal
If you need more precision, you can increase the precision of the decimal value of 1.0 (i.e. to 1.000, 1.0000000, etc).
Use window functions and proper division:
select orderstatusName, counts * 1.0 / total_counts
from (select t.*, sum(counts) over () as total_counts
from tbl
) t;
The reason you are getting 0 is because SQL Server does integer division when the operands are integers. So, 1/2 = 0, not 0.5.

Why is my output not exactly 2.39?

I need the output with 2 digit like 2.39 but I got the output 2.3980815347721822541966.
That is the problem I don't understand.
Here is my Query.
SELECT M.Description,A.Target,A.Actual,
CASE
WHEN A.Target > 0 THEN A.Actual / CONVERT(DECIMAL(18,2),A.Target)
ELSE 0
END Achievement
FROM (
SELECT * FROM ProcessData PD
WHERE
ProcessYear = 2015 AND ProcessMonth = 1
AND DepotID = 6 AND ModuleID =1
) A
LEFT OUTER JOIN Measure M
ON M.ID = A.MeasureID
You need to format the whole expression rather than just the divisor:
So rather than
THEN A.Actual / CONVERT(DECIMAL(18,2),A.Target)
Change it to:
THEN CONVERT(DECIMAL(18,2), A.Actual / A.Target)
Note that I would expect 2.398 to round to 2.40 (which is what the code I posted will do) - are you sure you want to round down always? If so, look at the ROUND function as well.
THEN CONVERT(DECIMAL(18,2), ROUND(A.Actual / A.Target, 2, 1)

Measuring distance between two Lat/Lng points

I am having issues trying to return the closest location to the user via an SQL statement. To test I am using the exact same coordinates, here is what I have:
SQL:
SELECT `companies`.`customerName` ,
(3959 *
ACOS(
COS(
RADIANS(37.367485) * COS(RADIANS(`locations`.`gps_lat`)) *
COS(
RADIANS(`locations`.`gps_lng`) - RADIANS(-77.399994) +
SIN(RADIANS(37.367485)) * SIN(RADIANS(`locations`.`gps_lat`))
)
)
)
)
AS `distance`
FROM `locations`
JOIN `companies` ON `locations`.`co_id`
HAVING `distance` > 25
ORDER BY distance
LIMIT 0 , 10
Results:
| customerName | distance |
| SOME COMPANY | 1914.41747964854 |
locations table values:
gps_lat | gps_lng
37.367485 | -77.399994
I used the example from Google, I checked the formula a couple times and I can't seem to come up with where I went wrong. Any help is appreciated.
EDIT:
Since there seems to be some confusion on me knowing what I am doing:
The > was substituted to yield a result, 1914 is obviously greater then 25.
The application of this is passing user coordinates from an Android app to our web server. The Latitude and Longitude will be pulled from the $_GET values and cross-referenced from companies in our web servers MYSQL database.
The syntax above is just me checking my SQL statement in Mysql Workbench. Obviously I am looking for a zero value result.
I think I have solved this issue by changing from Googles example to the formula provided by "Adventures of an adopted yooper". Using his/her version of the Haversine Formula.
Note: The Google example above is using Haversine as well.
SQL:
SELECT `companies`.`customerName` ,
(2 * (3959 * ATAN2(
SQRT(
POWER(SIN((RADIANS(37.367485 - `locations`.`gps_lat` ) ) / 2 ), 2 ) +
COS(RADIANS(`locations`.`gps_lat`)) *
COS(RADIANS(37.367485 )) *
POWER(SIN((RADIANS(-77.399994 - `locations`.`gps_lng` ) ) / 2 ), 2 )
),
SQRT(1-(
POWER(SIN((RADIANS(37.367485 - `locations`.`gps_lat` ) ) / 2 ), 2 ) +
COS(RADIANS(`locations`.`gps_lat`)) *
COS(RADIANS(37.367485)) *
POWER(SIN((RADIANS(-77.399994 - `locations`.`gps_lng` ) ) / 2 ), 2 )
))
)
))
AS 'distance'
FROM `locations`
JOIN `companies` ON `locations`.`co_id`
HAVING distance < 25
ORDER BY distance
LIMIT 0 , 10
For those curious on my application, Final PHP:
GET Value: ?lat=37.367485&lng=-77.399994
$earth_radius_miles = 3959; // Earth radius in miles
$earth_radius_kilometers = 6371; // Earth radius in kilometers
$result_radius = 10000; // Maximum distance in either miles or kilometers
$get_lat = $_GET["lat"];
$get_lng = $_GET["lng"];
$dbSelect = mysql_query("SELECT `companies`.`customerName`,
(2 * (".$earth_radius_miles." * ATAN2(
SQRT(
POWER(SIN((RADIANS(".$get_lat." - `locations`.`gps_lat` ) ) / 2 ), 2 ) +
COS(RADIANS(`locations`.`gps_lat`)) *
COS(RADIANS(".$get_lat.")) *
POWER(SIN((RADIANS(".$get_lng." - `locations`.`gps_lng` ) ) / 2 ), 2 )
),
SQRT(1-(
POWER(SIN((RADIANS(".$get_lat." - `locations`.`gps_lat` ) ) / 2 ), 2 ) +
COS(RADIANS(`locations`.`gps_lat`)) *
COS(RADIANS(".$get_lat.")) *
POWER(SIN((RADIANS(".$get_lng." - `locations`.`gps_lng` ) ) / 2 ), 2 )
))
)
))
AS 'distance'
FROM `locations`
JOIN `companies` ON `locations`.`co_id`
HAVING distance < ".$result_radius."
ORDER BY distance
LIMIT 0 , 10")
or die(mysql_error());
Results:
[{"customerName":"SOME COMPANY","distance":"0"}]
I have tested these results with other coordinates and seems to be working perfectly. Haven't tested anything with great distance between the two points but my application doesn't require me to do so.
Ashok, you can calculate the distance between two cordinates by using the below formula:
where
R = radius of the earth (6,371 km)
Δlat = |lat2- lat1|
Δlong = |long2- long1|