AVG function not working - sql

I am working on SQL Server. I have a table that has an int column HalfTimeAwayGoals and I am trying to get the AVG with this code:
select
CAST(AVG(HalfTimeAwayGoals) as decimal(4,2))
from
testtable
where
AwayTeam = 'TeamA'
I get as a result 0.00. But the correct result should be 0.55.
Do you have any idea what is going wrong ?

select
AVG(CAST(HalfTimeAwayGoals as decimal(4,2)))
from
testtable
where
AwayTeam = 'TeamA'

If the field HalfTimeAwayGoals is an integer, then the avg function does an integer average. That is, the result is 0 or 1, but cannot be in between.
The solution is to convert the value to a number. I often do this just by multiplying by 1.0:
select CAST(AVG(HalfTimeAwayGoals * 1.0) as decimal(4, 2))
from testtable
where AwayTeam = 'TeamA';
Note that if you do the conversion to a decimal before the average, the result will not necessary have a scale of 4 and a precision of 2.

Can you try dividing by 1.00 to convert the integer into decimal?
select
AVG(HalfTimeAwayGoals/1.00) as average
from
testtable
where
AwayTeam = 'TeamA'

I used the /1.00 OR /1.0000 trick on various databases to do the job. Unfortunately, I don't have access MS-SQL to try it. The division of integer by 1.00 will change the integer to decimal.
SELECT AVG(integerfield/1.00) FROM table

In MySQL
SELECT AVG(integerfield) FROM table
gives me 4 decimal points.
If I do
SELECT AVG(integerfield/1.00) FROM table
I get 8 decimal points.

Related

Want decimal result Amazon Redshift

I am trying to calculate the average ice creams a kid will have during summer.
I want the result to have 2 decimals.
Query:
Select day, (sum(ice_cream_cones) *1.0)/(select count(kids))
From t1 Group by 1
The result I get is something like 1.0003. I only want 2 decimal points.
Any suggestions?
You can do this with round
Select day, round((sum(ice_cream_cones) *1.0)/(select count(kids) ), 2)
From t1
Assuming your source data are integers...
SUM(ice_cream_cones) * 100 / COUNT(kids) / 100.0
Or, cast your existing calculation to a decimal?
CAST(<calc> AS DECIMAL(8,2))

Trim a decimal to 2 places Bigquery

I am currently running a query that runs a sum function and also divides this number. Currently I get values like 0.0904246741698848, and 1.6419814808335567. I want these decimals to be trimmed to 2 spaces past the decimal point. Their schema is a float. Here is my code. Thanks for the help.
#standardSQL
SELECT
Serial,
MAX(createdAt) AS Latest_Use,
SUM(ConnectionTime/3600) as Total_Hours,
COUNT(DISTINCT DeviceID) AS Devices_Connected
FROM `dataworks-356fa.FirebaseArchive.Firebase_ConnectionInfo`
WHERE PeripheralType = 1 or PeripheralType = 2 or PeripheralType = 12
GROUP BY Serial
ORDER BY Latest_Use DESC
#standardSQL
WITH `data` AS (
SELECT 0.0904246741698848 AS val UNION ALL
SELECT 1.6419814808335567
)
SELECT val, ROUND(val, 2) AS rounded_val
FROM `data`
for example, assuming your want apply this to your Total_Hours column :
#standardSQL
SELECT
Serial,
MAX(createdAt) AS Latest_Use,
ROUND(SUM(ConnectionTime/3600),2) AS Total_Hours,
COUNT(DISTINCT DeviceID) AS Devices_Connected
FROM `dataworks-356fa.FirebaseArchive.Firebase_ConnectionInfo`
WHERE PeripheralType = 1 OR PeripheralType = 2 OR PeripheralType = 12
GROUP BY Serial
ORDER BY Latest_Use DESC
I found that rounding was problematic if my data had a whole number such as 2.00 and I needed all of my data to reflect 2 decimal places as these were for prices that end up getting displayed. Big Query was returning 2.0 no matter what I specified to round to using ROUND.
Assuming you're working with data that never surpasses 2 decimal places, and it is stored as a STRING, this code will work (if it's more decimal places, add another 0 to the addition for each space).
FORMAT("%.*f",2,CAST(GROSS_SALES_AMT AS FLOAT64) + .0001)
This will take a float in BigQuery and format it with two decimal points.
CAST(SUM(ConnectionTime/3600) AS STRING FORMAT '999,999.99')
Note: Add a a currency symbol (e.g., $) for currency ($999,999.99).
Example:
You can always use the round() function.
If you are looking for precision after decimal (as using round will round-off the values) you can use substr(str(value),precision) which will give exact output after decimal.

Select Query: To Show Average of Columns in Decimal

I want to get value in decimal while calculating averave of column values in select query. For that I have used below query. But the value comes as 3.0 instead of 3.6. Is there any solution for that?
SELECT P.ANSW_ONE,P.ANSW_TWO,P.ANSW_THREE,P.ANSW_FOUR,P.ANSW_FIVE,
CAST(((P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE)/5) AS DECIMAL(10,1)) AS ANSW_AVG
FROM FEEDBACK P
CAST the whole SUM instead of the result and use 5.0 just to force it to be decimal instead of integer.
SELECT P.ANSW_ONE,
P.ANSW_TWO,
P.ANSW_THREE,
P.ANSW_FOUR,
P.ANSW_FIVE,
(CAST((P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE) DECIMAL(10,1) /5.0)) AS ANSW_AVG
FROM FEEDBACK P
Try This
SELECT
P.ANSW_ONE,
P.ANSW_TWO,
P.ANSW_THREE,
P.ANSW_FOUR,
P.ANSW_FIVE,
CAST(CAST(P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE AS DECIMAL(10,1))/5 AS DECIMAL(10,1)) AS ANSW_AVG
FROM FEEDBACK P
Cast the sum before dividing by 5 and then again cast the result

How to use count(*) and Division Operation in SQL statements

I'm loading big data into database,
i want to know how this process going.
i use
select count(*) from table
to check how many rows loaded.
and now i want to get a Percentage of the process.
i tried:
select ( count(*)/20000 ) from table
and
select cast( ( count(*)/20000 ) as DECIMAL(6,4) ) from table
but they all return 0 ,
so how can i do this?
And better if it can show the percentage .
thanks
Integer division returns an integer, the decimal part is truncated. You could divide by 20000.0:
select ( count(*)/20000.0 ) from table
Demo
MSDN / (Divide)
If an integer dividend is divided by an integer divisor, the result is
an integer that has any fractional part of the result truncated.
Select CONVERT(DECIMAL(6,4),COUNT(*)) / CONVERT(DECIMAL(6,4),20000) FROM TABLE
-
Its important that you match the type explicitly because not all numbers are integers and not all decimals are the same. DECIMAL(6,4) is effectively its own data type which is not the same as DECIMAL(6,3).

How do not to round the number in SQL

I have a query like this:
Select Customer,JobType,sum(SThours),
sum(OThours),SortMonth,
str((sum(OThours)/sum(SThours)),5,2)AS Ratios
from #data
group by Customer,JobType,SortMonth
Sum (SThours): 688
sum(OThours): 618
The ratio should be 618/688=0.90 but my result is 1.00
I am new to SQL, and I need help. Thanks.
Try casting one or other side of the division to a float - to force floating point rather than integer division.
SELECT
Customer,
JobType,
sum(SThours),
sum(OThours),
SortMonth,
str((CAST(sum(OThours) AS FLOAT)/sum(SThours)),5,2) AS Ratios
FROM
#data
GROUP BY
Customer,
JobType,
SortMonth
Try casting the number to decimal
SELECT
Customer,
JobType,
sum(SThours),
sum(OThours),
SortMonth,
str((CAST(sum(OThours) AS DECIMAL)/sum(SThours) ),5,2) AS Ratios
FROM
#data
GROUP BY
Customer, JobType, SortMonth
Try this sample fiddle
it is simple example showing getting decimal values
Your problem is that you're performing an integer division, which will always result in an integer value in return.
You should cast the sums to a floating point numeric value (decimal should work) before dividing them.