Calculate average of a row in SQL Server - sql

I have the below table..the percent column is of type nvarchar
Data Percent1 Percent2 Percent3
1 3% 4% 6%
2 6% 8% 7%
3 8% 6% 8%
I have to calculate the Avg per line so I get results like
Data Avg
1 4.33%
I was trying to convert the %column into decimal so I can apply the average function
select
Case WHEN Isnumeric([Percent1]) = 1
THEN CONVERT(DECIMAL(18,2),Replace([Percent1],'%',''))
ELSE 0 END AS Percent1
from DashboardData
but I am just getting 0 values..I am guessing the outer function is running before the inner for some reason. Can someone please tell me how I can achieve this.
I know the IsNumeric function will make it 0 but I tried it before that and I was getting an exception that type is not a number.
Thanks

SELECT ISNUMERIC('3%') will return 0, as will all the rest of your values, so your else condition will always be the result.
Just drop the %
select
data,
(replace(Percent1,'%','') + replace(Percent2,'%','') + replace(Percent3,'%','')) * 1.0 / 3
Note, if any of these values are NULL you need to account for that because NULL + anything IS NULL.
Also, you don't want to lean on ISNUMERIC too heavy... it can produce some results you probably aren't expecting
select
ISNUMERIC('$') --money which is a numeric value
,ISNUMERIC('1e4') --scientific notation
,ISNUMERIC('45D-1') --old scientific notation
,ISNUMERIC('.') --just the decimal portion of a float / decimal

Is this what you want?
select dd.*, s.average
from dashboarddata dd cross apply
(select avg(try_convert(numeric(10, 2), replace(pc, '%', ''))) as average
from values (percent1), (percent2), (percent3)) as v(pc)
) s;

Related

Redshift division result does not include decimals

I'm trying to do something really quite basic to calculate a kind of percentage between two columns in Redshift. However, when I run the query with an example the result is simply zero because the decimals are not being covered.
code:
select 1701 / 84936;
Output:
I tried :
select cast(1701 / 84936 as numeric (10,10));
but the result was 0.0000000000.
How could I solve this silly thing?
It is integer division. Make sure that at least one argument is: NUMERIC(accurate data type)/FLOAT(caution: it's approximate data type):
/ division (integer division truncates the result)
select 1701.0 / 84936;
-- or
SELECT 1.0 * 1701 / 84936;
-- or
SELECT CAST(1701 AS NUMERIC(10,4))/84936;
DBFiddle Demo
When mixing data types the order counts
Note that the order of the elements in a math expression counts for the data type of the result.
Let's assume that we intend to calculate the percentage unit_sales/total_sales where both columns (or numbers) are integers.
See and try with this code here.
-- Some dummy table
drop table if exists sales;
create table sales as
select 3 as unit_sales, 9 as total_sales;
-- The calculations
select
unit_sales/total_sales*100, --> 0 (integer)
unit_sales/total_sales*100.0, --> 0.0 (float)
100.0*unit_sales/total_sales --> 33.3 (float and expected result)
from sales;
The output
0 | 0.0 | 33.33
The first column is 0 (integer) because of 3/9=0 in an integer division.
The second column is 0.0 because SQL first got the integer 0 (3/9), and later, SQL converts it to float in order to perform the multiplication by 100.0.
The expected result.
The non-integer 100.0 at the beginning of the expression force a non-integer calculation.

How to divide columns with zeros and nulls

just a simple question but somehow I can't find an answer here.
I have two columns (A and B). Both contains numbers with zeros and null. I would like to get a division one by the other to get information about the ratio between each single row but I am getting ORA-01476.
I know the divisior is equal to zero but I would like to get in this row a number and not an error for whole query
A B
1 5
2 Null
3 0
NULL 3
0 4
4
I am using sql developer.
If you divide a number by zero you get an error, because the answer to such division is undefined. SQL, however, has a value for undefined: NULL. So make the result NULLinstead:
select a, b, case when b = 0 then null else a / b end as ratio
from mytable;
or
select a, b, a / case when b = 0 then null else b end as ratio
from mytable;
This is standard SQL and works in Oracle as well as in about every other RDBMS. Oracle also provides the function NULLIF as a shorter way to write the expression in the second query.
You can use nullif to return null instead of raising an error:
select A / nullif(B, 0) as division
from YourTable
If your numbers are stored as varchar, cast them to numbers before using them:
select to_number(A) / nullif(to_number(B), 0) as division
from YourTable

Division of two statements with count returns zero

I am new to SQL (using SQLiteStudio) and am trying to work with some of the aggregate functions. I want to find the proportion of a subset of my data where mass of individuals is less than 575, but the query keeps returning zero:
SELECT A/B*100
FROM (
SELECT COUNT(*) AS A
FROM Male
WHERE mass < 575 AND location = 'Hawaii')
,(
SELECT COUNT(*) AS B
FROM Male
WHERE location = 'Hawaii')
;
I have read other questions where the issue was having to declare the variable in question as a decimal, but I do not know how to change the constraint of the COUNT() function. Multiplying A*B works just fine.
You could simplify your query to one select statement and force casting by multiplication with 100.0 where .0 should do the trick
SELECT
(SUM(CASE WHEN mass < 575 THEN 1 ELSE 0 END) * 100.0) / COUNT(*)
FROM Male
WHERE location = 'Hawaii'
Try
SELECT A * 100 / B
or the intermediate result will be 0 because of integer division.

How to Divide two columns in DB2 SQL

I have disk capacities stored in 2 columns as CAPACITY_TOTAL and CAPACITY_USED. I need to present % utilization for which I need to divide CAPACITY_USED by CAPACITY_TOTAL as CAPACITY_USED/CAPACITY_TOTAL * 100.
I am using below Query:
select CAPACITY_USED / CAPACITY_TOTAL from TableName
which gives below error:
DB2 SQL Error: SQLCODE=-801, SQLSTATE=22012, SQLERRMC=null, DRIVER=4.15.82
I have casted my columns to decimal but even that doesn't work.
Error code 801 means your query was trying to divide by zero.
select CAPACITY_USED / CAPACITY_TOTAL from TableName
where CAPACITY_TOTAL IS NOT NULL and CAPACITY_TOTAL <> 0
OK, so SQLSTATE=22012 means you're trying to divide by zero. Apparently some of your rows contain nulls or zeroes in CAPACITY_TOTAL column and db fails to calculate the formula.
Try this query for better results:
SELECT CASE CAPACITY_TOTAL
WHEN 0 THEN 0
WHEN NULL THEN 0
ELSE CAPACITY_USED / CAPACITY_TOTAL
END AS UTILIZATION
FROM MY_TABLE
You may want to put some other meaningful return values for zeroes / nulls.
Alternatively, skip rows, where CAPACITY_TOTAL is null or zero:
SELECT CAPACITY_USED / CAPACITY_TOTAL AS UTILIZATION
FROM MY_TABLE
WHERE CAPACITY_TOTAL IS NOT NULL
AND CAPACITY_TOTAL > 0

'select count' when divided by another select count only returns when 1=1

I'm basically trying to get the percent of two select counts. In the example shown below, I should have a simple 2 / 6 which results in 33.33%. However when I run the query is only returns either 100% or 0%. Any help on why it does what it does would be fantastic
CONVERT(DECIMAL(4, 2),
(SELECT Count(driver)
FROM trh a
WHERE a.hn = trh.hn
AND a.driver = trh.driver
AND (a.finishposition < 5
AND a.finishposition IS NOT NULL
AND a.finishposition != 0 )) / Count(driver) ) * 100
Now that I try CONVERT(DECIMAL(4, 2), 2 / 6), this just returns 0.00 also
Okay you have to cast them as decimals
SQL Server does integer division. Just cast() one of the values to a decimal or floating type. For instance:
/ cast(Count(driver) as decimal(4, 2))