Want decimal result Amazon Redshift - sql

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))

Related

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

Calculate percentage between two columns in SQL Query as another column

I have a table with two columns, number of maximum number of places (capacity) and number of places available (availablePlaces)
I want to calculate the availablePlaces as a percentage of the capacity.
availablePlaces capacity
1 20
5 18
4 15
Desired Result:
availablePlaces capacity Percent
1 20 5.0
5 18 27.8
4 15 26.7
Any ideas of a SELECT SQL query that will allow me to do this?
Try this:
SELECT availablePlaces, capacity,
ROUND(availablePlaces * 100.0 / capacity, 1) AS Percent
FROM mytable
You have to multiply by 100.0 instead of 100, so as to avoid integer division. Also, you have to use ROUND to round to the first decimal digit.
Demo here
The following SQL query will do this for you:
SELECT availablePlaces, capacity, (availablePlaces/capacity) as Percent
from table_name;
Why not use a number formatting function such as format_number (or an equivalent one in your database) to format a double as a percentage? This example is generalized. The returned value is a string.
WITH t
AS
(
SELECT count(*) AS num_rows, count(foo) as num_foo
FROM mytable
)
SELECT *, format_number(num_foo/num_rows, '#.#%') AS pct_grade_rows
FROM t
This avoids the use of round and multiplying the numerator by 100.

AVG function not working

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.

Calculate an average as a percent?

This is a simple problem and I'm surprised I couldn't find an answer to it.
All I need, is to calculate the average of a column and have the output as a percent.
Select round(avg(amount)::numeric, 2)
From Table
All I need is to figure out how to make that a percent, right now it comes out as 12345.67, how would I convert that output to a percentage in the query?
Maybe you need something like this:
select avg(amount) * 100 / sum(amount)
from Table
Or you can add a percent sign to it like this:
select CAST(avg(amount) * 100 / sum(amount)as VARCHAR(max)) + '%' AS Perc
from Table
or you can just concatenate a sign to your query:
Select CAST(round(avg(amount)::numeric, 2)as VARCHAR(max)) + '%' AS Perc
From Table
Result / Total * 100 = Average
In your case, the Result is: avg(amount)::numeric
and the Total is whatever the maximum that amount could be.
Your best bet would be to use whatever tools are available to you. But there is a way you can do it as a query.
Try getting the average divided by the sum multiplied by 100.
So you want the average, like below and divided by the sum, and multiplied by 100 to get 100% of the sum.
select avg(amount) / sum(amount) * 100