How to extract first number after decimal point in value - sql

I have an age column which calculates age for each member in my report.The output is a whole number followed by a decimal point and numbers. I would like the first number only right after the decimal point .
I tried trunc but it gives me everything before the decimal and then the number I want after .Then I tried to trunc with a call out with a comma and it doesnt work.
trunc(age,',')
Example -
age 15.7
expected output 7

Here the mathematical answer
take the decimal part by susbriacting the whole part (trunc).
multiply by 10 and take the whole part
.
with age as (select 15.7231 age from dual)
select trunc(10*(age-trunc(age))) dp1 from age
DP1
----------
7

try like below
select substr(to_char(15.7,'9999.0'),-1,1) as col from dual
it will return 7

Multiply by 10, trunc it and take the remainder of the division by 10.
with age as (select 15.7231 age from dual)
select mod(trunc(10*age), 10) dp from age
Output:
DP
--
7

Related

Is there a numeric version of SUBSTR in BigQuery?

This may be a complete noob question. I have spent hours looking for a solution but haven't found one...
I am trying to capture the first digit of each number in a column of numbers. For example:
173563 = 1
247309 = 2
653638 = 6
etc
I know that I could do this using SUBSTR if the value were a string but that doesn't work for numbers. I have a work around but there must be a better way than how I'm currently doing it.
Any help would be much appreciated
with
-- Convert to string and get the first character
stage1 as (
SELECT
number
, SUBSTR(CAST(number AS STRING), 1, 1) AS cut_off
FROM my_table
),
-- Convert back to a numeric value
stage2 as (
SELECT
number
, CAST(cut_off AS NUMERIC) AS cut_off,
FROM stage1
)
select
number,
cut_off
from stage2
You can use below "trick"
with `project.dataset.table` as (
select 173563 number union all
select 247309 union all
select 653638
)
select number, left('' || number, 1) cut_off
from `project.dataset.table`
with output
Obviously, such a trick allows you to use any string function to meet your needs
You can do this all in one expression:
CAST(LEFT(CAST(number AS STRING), 1) as int64)
If the length of the number is always 6 digits, you can use arithmetic:
FLOOR(number / 100000)
Or:
DIV(number, 100000)

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.

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.

group yearmonth field by quarter in sql server

I have a int field in my database which represent year and month like 201501 stands for 2015 Jan,
i need to group by reporting_date field and showcase the quarterly data .The table is in the following format .Reporting_date is an int field rather than a datetime and interest_payment is float
reporting_date interest_payment
200401 5
200402 10
200403 25
200404 15
200406 5
200407 20
200408 25
200410 10
the output of the query should like this
reporting_date interest_payment
Q1 -2004 40
Q2 -2004 20
Q3 -2004 40
Q4 -2004 10
i tried using the normal group by statement
select reporting_date , sum(interest_payment) as interest_payment from testTable
group by reporting_date
but got different result output.Any help would be appreciated
Thanks
before grouping you need to calculate report_quarter, which is equal to
(reporting_date%100-1)/3
then do select
select report_year, 'Q'+cast(report_quarter+1 as varchar(1)), SUM (interest_payment)
from
(
select
*,
(reporting_date%100 - 1)/3 as report_quarter,
reporting_date/100 as report_year
from #x
) T
group by report_year, report_quarter
order by report_year, report_quarter
I see two problems here:
You need to convert reporting_date into a quarter.
You need to SUM() the values in interest_payment for each quarter.
You seem to have the right idea for (2) already, so I'll just help with (1).
If the numbers are all 6 digits (see my comment above) you can just do some numeric manipulation to turn them into quarters.
First, convert into months by dividing by 100 and keeping the remainder: MOD(reporting_date/100).
Then, convert that into a quarter: MOD(MOD(reporting_date/100)/4)+1
Add a Q and the year if desired.
Finally, use that value in your GROUP BY.
You didn't specify which DBMS you are using, so you may have to convert the functions yourself.

trunc and round function in sql

Is trunc and round the same with negative arguments?
SQL> select round(123456.76,-4) from dual;
ROUND(123456.76,-4)
-------------------
120000
SQL> select trunc(123456.76,-4) from dual;
TRUNC(123456.76,-4)
-------------------
120000
No, behavior depends on the value of the significant digit (the 3rd digit (the 3) is the significant one in your case, as it is below 5 round and trunc do the same )
try select trunc(125456.76,-4) from dual (result is 120000) vs select round(125456.76,-4) from dual (result is 130000). Now when the significant digit is 5 (or higher) the results of trunc and round differ.
ROUND is related to round figure of given value.
TRUNC is related to truncation of given values.
In round case of given example, four places till 4th place prior to decimal point padded with 0.
But in trunc case, four places till 4th place prior to decimal point replacd with 0.
TRUNC - depending on second parameter it returns specified decimal places that is specified in second argument. Ex:
trunc(25.656) -- 25
trunc(25.656, 1) -- 25.6
trunc(25.656, 2) -- 25.65
ROUND - round off the given number to the nearest value. Ex:
round(66) -- 70
round(64) -- 60
round(65.7) -- 66
round(65.3) -- 65