Convert SQL query into MYSQL - 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

Related

SQL use FORMAT() on a SUM()

I want to use FORMAT on SUM to produce a currency style format with commas and no decimal places. I'm trying the following using MySQL 5.7:
SELECT FORMAT(SUM(x.07_17 / fx.07_17), 0) AS total.....
The problem is this changes the data drastically. Without the format, I get the correct result of SUM 350914 but with the format, in place, I get 350, so just the first 3 numbers.
What is it I'm doing wrong?
You can check the documentation to see how each parameters works for the FORMAT function https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format
This query shows you different style to display your data (Sql fiddle example)
SELECT SUM(c1 / c2) AS total1
, CONCAT(FORMAT(SUM(c1 / c2), 3, 'fr_FR'), ' €') AS total2
, CONCAT('$', FORMAT(SUM(c1 / c2), 3)) total3
FROM ( SELECT 148277 c1
, 5.1561 c2 ) t

mysql get difference from the result of 2 fields queried

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

How does one construct a query that only returns this months rows, based on Timestamp?

I'm curious what the right way is to construct a query where the rows are pulled based on a timestamp that represents a specific month. Given that different months have different numbers of days, is there a way to generate a query that always gives you the rows where the timestamp contains the current month so that the results would only include the current month?
Do you mean something like this
SELECT * FROM tbl WHERE
MONTH(timesp) = MONTH(NOW()) AND
YEAR(timesp) = YEAR(NOW());
You can use the FROM_UNIXTIME() function:
SELECT *
FROM tableName
WHERE MONTH(FROM_UNIXTIME(timestampField))==6
Just use MONTH:
select *
from foo
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
Try this sql.
select *
from yourtable
where yourdatefield>=DATE_SUB(CURDATE(),INTERVAL 1 MONTH);
You're looking for something like this:
SELECT * FROM table where MONTH(date_row) = $month;
If you have an index on your date field, then this is efficient (T-SQL syntax, the idea applieas to any RDBMS though)
SELECT
*
FROM
tableName
WHERE
dateTimeField
BETWEEN
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
AND
-- add one month, subtract one day
DATEADD(mm, 1,
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
) - 1
Of course any other method to get two datetime values in the right range would work.
SQL Server has LEFT(CONVERT(varchar, GETDATE(), 120), 8) + '01' to convert a datetime to string, other Db servers have their own functions to do the same. Maybe you can calculate the two values in the calling application more easily - how you get them, is not the point.
The point is that BETWEEN can use an index, whereas the other solutions that work with WHERE MONTH(dateTimeField) = 6 will trigger a table scan, which is about the slowest operation you can do on a table.

Is any way to convert decimal to time in MySQL?

I created a field called 'hours_spent' in MySQL using the decimal datatype to store time. The values are stored like this 1.30, 2.30 etc... (for 1hr30min, 2hr30min).
I want to calculate the sum of various time values.
The sum of time is not what I expected: 1.30 + 2.30 = 3.60, whereas I expected 4.00.
I used the SUM function in MySQL to count the hours_spent field. If the values are 0.30 + 1.50 = 1.80, whereas I expected 2.20.
My first mistake was to use the decimal type instead of the time datatype, but I cannot change datatype.
So, is there any way to sum the time values and get result as I expect?
Thanks
I prepared you a demo at sqlfiddle, you can try it there if you want:
http://www.sqlfiddle.com/#!2/c9afc/2
Here are the query samples:
select #indexer:=instr(dateasdecimal, '.')
, left(dateasdecimal, #indexer-1) * 60 + substr(dateasdecimal, #indexer+1) as totalMinutes
from testtable;
select #indexer:=instr(dateasdecimal, '.')
, sum(left(dateasdecimal, #indexer-1) * 60 + substr(dateasdecimal, #indexer+1)) as totalMinutes
from testtable;
Note: Please don't forget to accept answers to your questions:
https://meta.stackexchange.com/a/65088/200585
To convert a decimal into seconds, you could use this:
truncate(hours_spent,0)*60+(hours_spent-truncate(hours_spent,0))*100
and then you can do the sums easily. Then you can convert back seconds to the decimal format with this:
truncate(seconds/60,0)+truncate(mod(seconds, 60)/100,2)
You could always turn the decimals into a string, cast as time, then sum that time using time_to_sec and produce a formatted time with sec_to_time. Of course, it would be much better to be storing those times a different way, even if it involves converting the entire dataset.
SELECT sec_to_time(sum(time_to_sec(goodTime))) FROM (
SELECT CAST(badTime AS TIME) AS goodTime FROM (
SELECT REPLACE(badTime, '.', ':') AS badTime FROM (
SELECT CAST(badTime AS dec(4,2)) AS badTime FROM (
SELECT 1.3 AS badTime
UNION select 2.3
) z
) y
) x
) w

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