mysql get difference from the result of 2 fields queried - mysql

I'm not good at sql but I can create,understand common SQL queries. While scouring the net it seems its hard to find a befitting way on this query.
I have a query which is
SELECT COUNT(`BetID`),
FORMAT(SUM(`BetAmount`),0),
FORMAT(SUM(`Payout`),0),
ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2),
ROUND((((SUM(`BetAmount`) + SUM(`Payout`)) / SUM(`Payout`)) * 100),2)
FROM `betdb`
I would like to subtract the result of
FORMAT(SUM(`BetAmount`),0)
and
FORMAT(SUM(`Payout`),0)
Any other ideas to execute subtraction in this mysql query?

If you want the numbers rounded before subtracting them (which seems to be the case when you want to subtract the formatted numbers), you'll need to round them first to the same precision as the formatting, subtract and lastly format the result;
SELECT COUNT(`BetID`),
FORMAT(SUM(`BetAmount`),0),
FORMAT(SUM(`Payout`),0),
FORMAT(ROUND(SUM(`BetAmount`),0) - ROUND(SUM(`Payout`),0),0) diff,
ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2),
ROUND((((SUM(`BetAmount`) + SUM(`Payout`)) / SUM(`Payout`)) * 100),2)
FROM `betdb`
A simple SQLfiddle to test with.

Use FORMAT((SUM(BetAmount) - SUM(Payout)),0)
Try this:
SELECT COUNT(`BetID`),
FORMAT(SUM(`BetAmount`),0),
FORMAT(SUM(`Payout`),0),
FORMAT((SUM(`BetAmount`) - SUM(`Payout`)),0),
ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2),
ROUND((((SUM(`BetAmount`) + SUM(`Payout`)) / SUM(`Payout`)) * 100),2)
FROM `betdb`

You could also try using a join statement so that the calculation is only done once:
SELECT *,t.BetTotal - t.PayoutTotal as Difference
FROM (
SELECT
COUNT(`BetID`) AS Count,
FORMAT(SUM(`BetAmount`),0) as BetTotal,
FORMAT(SUM(`Payout`),0) as PayoutTotal,
ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2),
ROUND((((SUM(`BetAmount`) + SUM(`Payout`)) / SUM(`Payout`)) * 100),2)
FROM `betdb`
) as t

Related

MYSQL to DB2 sql

Need some help to convert below MYSQL query to DB2 query:
SELECT FROM_UNIXTIME(CEILING((UNIX_TIMESTAMP(count_datetime))/300)*300) AS t,
sum(count_web) as web,
sum(count_mobile) as mobile,
sum(count_total) as total
from clicks_user_count GROUP BY t
ORDER BY `t` DESC
CREATE OR REPLACE FUNCTION FROM_UNIXTIME (P_UTS BIGINT)
RETURNS TIMESTAMP
CONTAINS SQL
DETERMINISTIC
NO EXTERNAL ACTION
RETURN TIMESTAMP('1970-01-01-00.00.00') + CURRENT TIMEZONE + P_UTS SECONDS;
I thinks that's the equivalent to your query
SELECT
timestamp(date(count_datetime)) + (midnight_seconds(count_datetime) / 300 * 300) seconds AS t,
sum(count_web) as web,
sum(count_mobile) as mobile,
sum(count_total) as total
from clicks_user_count
GROUP BY timestamp(date(count_datetime)) + (midnight_seconds(count_datetime) / 300 * 300) seconds
order by t
Below SQL assisted by nfgl able to produce same result in DB2. Thx you.
SELECT
timestamp(date(count_datetime)) + (midnight_seconds(count_datetime) / 300 * 300) seconds AS t,
sum(count_web) as web,
sum(count_mobile) as mobile,
sum(count_total) as total
from clicks_user_count
GROUP BY timestamp(date(count_datetime)) + (midnight_seconds(count_datetime) / 300 * 300) seconds
order by t

Convert SQL query into MYSQL

CONVERT(nvarchar(4), t/60) + '.' + CONVERT(nvarchar(4), t % 60) as t
Select CONCAT(FLOOR(t / 60), '.', MOD(t, 60)) as t
from (SELECT avg(TIMESTAMPDIFF(second,tur.start,tur.[end])) as t
FROM tblUserTracking tur where tur.start
between DATE_FORMAT(p_FromDt,'%m/%d/%Y')
and TIMESTAMPADD(DAY,1,DATE_FORMAT(p_Todt,'%m/%d/%Y')) ) as tbl1
In MySQL, use CONCAT():
CONCAT(FLOOR(t / 60), '.', MOD(t, 60)) as t
I assume t is an integer and you want integer division.
It looks like you are trying to format a time. If so, your code doesn't look right in either database. I might suggest that you ask a new question with sample data and desired results. In particular, this will product '5.1' and '5.10' for 301 seconds and 310 seconds respectively. Those look about the same to most people.
you can use this link to convert query
http://www.sqlines.com/online

SELECT not returning anything using HAVING clause

I'm trying to get the total percentage off and only return the matches >+ 80. However, this doesn't return any results:
SELECT * FROM products WHERE Available=1 AND Merchant='Amazon' HAVING (LowestUsedPrice - LowestNewPrice) / LowestNewPrice * 100 >= ?
Am I using HAVING correctly?
HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
HAVING is applied after the aggregation phase and must be used if you want to filter aggregate results.
Your query is wrong.
What you can do is do the conditioning in where clause only.
SELECT *
FROM products
WHERE Available=1
AND Merchant='Amazon'
AND (LowestUsedPrice - LowestNewPrice) / LowestNewPrice * 100 >= ?
As per I understand you wanna use having to filter whereas you may use just where condition.
About returning results, your query will produce syntax error. If you use as following and don't get any result then obviously it is because of conditions and your data. In that case if you provide data, you may get some help.
SELECT * FROM products
WHERE Available=1
AND Merchant='Amazon'
AND (LowestUsedPrice - LowestNewPrice) / LowestNewPrice * 100 >= ?
SELECT *, (LowestUsedPrice - LowestNewPrice) / LowestNewPrice * 100 as percentage FROM products WHERE Available=1 AND Merchant='Amazon' HAVING percentage >= ?
Your main problem is that your percentage formula is wrong. Use
((LowestUsedPrice - LowestNewPrice) / LowestNewPrice) * 100
or
(LowestUsedPrice - LowestNewPrice) * 100 / LowestNewPrice
The way you are using will do something like
(20 - 8) / 15 * 100
12 / 1500 = 0.008
And you need
1200 / 15 = 80
Add this fix to the solution on other answers

creating a random number using MYSQL

I would like to know is there a way to select randomly generated number between 100 and 500 along with a select query.
Eg: SELECT name, address, random_number FROM users
I dont have to store this number in db and only to use it to display purpose.
I tried it something like this, but it can't get to work..
SELECT name, address, FLOOR(RAND() * 500) AS random_number FROM users
Hope someone help me out.
Thank you
This should give what you want:
FLOOR(RAND() * 401) + 100
Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min> generates a number between <min> and <max> inclusive.
Update
This full statement should work:
SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number`
FROM users
As RAND produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
Additional to this answer, create a function like
CREATE FUNCTION myrandom(
pmin INTEGER,
pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
RETURN floor(pmin+RAND()*(pmax-pmin));
END;
and call like
SELECT myrandom(100,300);
This gives you random number between 100 and 300
You could create a random number using FLOOR(RAND() * n) as randnum (n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)...
these both are working nicely:
select round(<maxNumber>*rand())
FLOOR(RAND() * (<max> - <min> + 1)) + <min> // generates a number
between <min> and <max> inclusive.
This is correct formula to find integers from i to j where i <= R <= j
FLOOR(min+RAND()*(max-min))

SQL Query issue: MySQL

The following query returns null in MySQL. I check all things like cos, acos individually. But this query is returning NULL. Kindly help me.
altitude and latitude is the geo location of the places
select
acos(sin(74.338372290294) * sin(altitude) +
cos(74.338372290294) * cos(altitude) *
cos(latitude) - (31.552278760192)) as omg
from shk_resturants
If any of the values in your table (latitude or altitude) are NULL, the result may be NULL also. Try to use the function
COALESCE(value, ...)
e.g.
select
acos(sin(74.338372290294) * sin(COALESCE(altitude, 0)) +
cos(74.338372290294) * cos(COALESCE(altitude, 0)) *
cos(COALESCE(latitude, 0)) - (31.552278760192)) as omg
from shk_resturants
This returns 0 for the columns, that have NULL-values.
See: MySQL Comparsion-Operators and: MySQL Math-Functions
acos(x) is only valid if
-1 <= x <= 1
As can be seen here:
http://en.wikipedia.org/wiki/Inverse_trigonometric_function
So I'm guessing you put the parentheses wrong. You might have wanted to do something like
cos(latitude - (31.552278760192)) -- or
cos(latitude) - cos(31.552278760192)
at the end...? My trigonometry is too rusty to tell...