SQL Server wrong mathematical result - sql

I have this statement:
Select (30 - 5) * 700 / 30 as A , 700 - (5 * 700 / 30) as B
which has two ways to calculate the same equation.
These two equations should result in 583.33 if you made them by your calculator
but the previous statement results in 583 for field A, and 584 for field B.
Both are wrong and both are integer not decimal.
I want to know what's the right way to write this statement so I can get 583.33.
Thanks

Your expression is implicitly using an INT datatype. Try it this way to allow it to use a DECIMAL datatype
Select (30.000 - 5.000) * 700.000 / 30.000 as A ,
700.000 - (5.000 * 700.000 / 30.000) as B

Use Cast function:
As next:
Select Cast((30 - 5) * 700 as DECIMAL(19,2) ) / 30 as A ,
700 - ( Cast (5 * 700 as decimal (19,2 )) / 30) as B
Result:
A B
583.333333 583.333334

Related

Where clause on numbers dont give expected results

I have the following sample data in table_a.value:
abcdef 10 / 20 / 30 adfadsf
adfadsf 1000 / 10,5 / 300.5 kjbkjj
adsfadsf 0.1 / 8000 / 0,0005 asdfdasf
adsfasdf dfkjaf dsaflkjadslf asdfasdf 100 / 10.5 dslfjalksdf 500
adfdasf 50 sdlfkja 1000 alfdkjasf 50.5
ajkfdha asfdjlas dslkfjsdf
I want to filter out with a where clause row 1 to 3 where it has the following condition:
where table_a.value like '%number / number / number%'.
Expected results would be:
abcdef 10 / 20 / 30 adfadsf
adfadsf 1000 / 10,5 / 300.5 kjbkjj
adsfadsf 0.1 / 8000 / 0,0005 asdfdasf
I tried to make it work with the following code:
Where table_a.value like '%[0-9.,] / [0-9.,] / [0-9.,]%'
However, this is not giving me the expected results.
Could somebody guide me in the right direction?
SQL Server is not very good at doing this. You might be able to simplify your problem. For instance, you can get the same rows just by looking for two slashes surrounded by spaces:
where a_value like '% / % / %'
You can ensure that the central component is a number and that there are numbers before and after the spaces:
where a_value like '%[0-9] / [0-9]% / [0-9]%' and
a_value not like '%[0-9] / [0-9]%[^0-9]% / [0-9]%'
This is not 100% equivalent to what you want to do, but it might be sufficient for your purposes.
SQL Server does not expose any true regular expression functionality via TSQL. The pattern syntax does not have any sort of support for quantifiers.
In this case you could first use TRANSLATE to ensure that all characters in the set 0-9., are denoted as 0 and then use a couple of nested replaces to collapse down contiguous series of 0 to be represented as 12. (REPLACE(REPLACE(..., '0', '12'),'21',''))
The initial TRANSLATE ensures the input to that step can't have any other 1 or 2 characters.
Then check that the result is LIKE '%12 / 12 / 12%'
SELECT *
FROM ( VALUES ('abcdef 10 / 20 / 30 adfadsf'),
('adfadsf 1000 / 10,5 / 300.5 kjbkjj'),
('adsfadsf 0.1 / 8000 / 0,0005 asdfdasf'),
('adsfasdf dfkjaf dsaflkjadslf asdfasdf 100 / 10.5 dslfjalksdf 500'),
('adfdasf 50 sdlfkja 1000 alfdkjasf 50.5'),
('ajkfdha asfdjlas dslkfjsdf') )V(Col)
WHERE REPLACE(REPLACE(TRANSLATE(Col, '123456789.,', '00000000000'), '0', '12'), '21', '') LIKE '%12 / 12 / 12%'
(Fiddle)

How do you calculate using sum in SQL Server

I am trying something like this:
select sum(R_Value) ,((5/cast(sum(R_Value) as int)) * 100.000000000)
from R_Rating
where R_B_Id = 135
But I keep getting value 0, sum(R_Value) = 6, so I just want a percentage out of (5/sum(R_Value)) * 100.
How can I get this?
I have a rating of 5 so each user has a rating they can make select from 1 to 5, so what i need is a formula that takes in the sum and takes into account how many users have rated and give us a result from 1 to 5 in the end
Something like this may work but i need to round up to one decimal place to get a whole number.
select sum(R_Value), ((count(*)/cast(sum(R_Value) as float)) * 10)
from R_Rating
where R_B_Id = 135
To get the average rating you need to force floating point algebra. For example:
select 1.0 * sum(R_Value) / count(*)
from R_Rating
where R_B_Id = 135
Then, if your query selects three rows with the values: 1, 4, and 5, then this query will return 3.33 stars as the average. That is:
= 1.0 * (1 + 4 + 5) / 3
= 1.0 * 10 / 3
= 10.0 / 3
= 3.33333333
I recommend writing this as:
select sum(R_Value) ,
(500.0 / sum(R_Value))
from R_Rating
where R_B_Id = 135;
This avoids an integer division.

Decimal Places Puzzle

I have a Query that incorporates some calcualted fields. The 'Total' Column produces a value with 2 decimal places but the Commission and Net_Receipt Columns have 4 decimal places despite the code looking exactly the same format. Can anyone tell me why and how to correct the latter two to 2 DP's.
SELECT `exhibition_sales`.`name`,
`exhibition_sales`.`category`,
`exhibition_sales`.`catologue_number`,
`exhibition_sales`.`title`,
`exhibition_sales`.`quantity`,
`exhibition_sales`.`unit_price`,
`exhibition_sales`.`commision_rate`,
`exhibition_sales`.quantity * `unit_price` AS `Total`,
`exhibition_sales`.quantity * `commision_rate` * unit_price AS `Commision`,
`exhibition_sales`.quantity * `unit_price` - `quantity` * `unit_price` * `commision_rate` AS `Net_Receipt`
FROM exhibition_sales
ORDER BY `exhibition_sales`.`name` ASC
The rules for the output format of decimal places is very convoluted. If you want a particular number, then just cast to the format you want:
select . . .,
cast(`exhibition_sales`.quantity * `commision_rate` * unit_price as decimal(10, 2)) AS `Commision`,
cast(`exhibition_sales`.quantity * `unit_price` - `quantity` * `unit_price` * `commision_rate` as decimal(10, 2)) AS `Net_Receipt`
There is some explanation in the documentation.
Assuming you are on SQL-Server, the rules of multiplication and division with numerics apply:
Total is the multiplication of a (x, 0)-value with a (x, 2)-value, so the final scale will be 0+2 = 2. Hence 5 * 2.00 == 10.00
Commission is the multiplication of a (x, 0)-value, a (x, 2)-value and a (x, 2)-value so the final scale will be (0+2)+2 = 4. Hence 5 * 2.00 * 4.00 == 40.0000
Net_Receipt is the sum of two multiplications; the final scale will be max(s1 + s2, s3 + s4), that is max(0 + 2, 2 + 2) == 4. Hence 5 * 2.00 + 1.00 * 3.00 == 13.0000

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

Calculate percentage in MS SQL Server with int columns

I am trying to calculate the total amount for charity. Each row has a bid amount and a charity percentage.
The structure of the fields looks like this:
CurrentBid INT
CharityPercentage INT <-- 0-100, where 100 is donating all to charity
So i tried this:
SELECT CurrentBid, CharityPercentage, CurrentBid * (CharityPercentage / 100) AS TotalCharity FROM Items
However it yields this:
50 100 50
70 100 70
25 50 0
50 25 0
30 10 0
55 15 0
It works as long as the percentage is 100. Anything below and its 0. My guess is that it has to do with the int column.
Any ideas on how to solve it? I have also tried to convert the int using a CAST in the select statement but that did not work. Its a very big procedure to change the INT column to something else.
Explicitly make at least one value a decimal/float/etc. In your case, you already have a literal numeric value, 100; so, simply change it to, 100.0:
CurrentBid * CharityPercentage / 100.0 AS TotalCharity
don't CAST -- instead, just multiply by 1.00. This does the CASTing implicitly.
SELECT CurrentBid, CharityPercentage, (1.00 * CurrentBid * CharityPercentage) / 100 AS TotalCharity FROM Items