MYSQL - Max(Date) gives me right Date but wrong Value - mysql

So I am querying a specific measurement based of the last date inserted using MAX
The last occurency is this one:
Measurement Date_insert
9.039999961 2021-03-30 11:57:2
When I try to query it like this:
SELECT m.measurement, MAX(m.date_insert) FROM measurements m
I get:
Measurement Date_insert
0.000000000 2021-03-30 11:57:2
The date keeps the same which shows me that I queried the right date
but how is it possible that the measurement changes value?
Any help would be grateful!

You should do that
SELECT m.measurement, m.date_insert
FROM measurements m
order by m.date_insert desc
limit 1
Your query does not return the correct results because you mix "normal" column selects with aggregation. MySQL supports that sadly. It returns strange results. Other DB engines throw an error for your query.

It's returning 0.000000000 as measurement from the first (any) row and MAX(m.date_insert) is returning max value from date_insert column.
It's possible that 0.000000000 and 2021-03-30 11:57:2 even do not exist in same row.
Please avoid this query if your intention is to get the max date_insert along with the value of measurement column from same row. Instead use just order by clause with Limit 1 as suggested by #juergen d.
But if there are multiple measurement value for a single date_insert then you can use group by clause to find the max(measurement) for the highest date_inert value. Here goes the example:
Schema:
create table measurements( Measurement float, Date_insert datetime);
insert into measurements values(0.000001000 ,'2021-03-30 11:57:5');
insert into measurements values(9.039999961 ,'2021-03-30 11:57:5');
insert into measurements values(0.000000000 ,'2021-03-30 11:57:2');
Set sql_mode:
set sql_mode=only_full_group_by;
Query:
SELECT m.date_insert, max(m.measurement)measurement
FROM measurements m
group by m.date_insert
order by m.date_insert desc
limit 1
date_insert
measurement
2021-03-30 11:57:05
9.04
db<>fiddle here

Related

How to select the bigger date between 2 columns?

I have a table 'processes' with the following columns :
id
date_creation
date_lastrun
For example I have the following entries:
id;date_creation;date_lastrun
1;2022-01-01 00:00:00;2022-02-01 00:00:00
2;2022-03-01 00:00:00;NULL
I want to select the element with the bigger date in MySQL
I can do
SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
It's OK it works but now I want to get the element with the bigger date compared to a specific date time.
I tried :
SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
WHERE DATE(lastdate) > "2022-03-01"
but it returns *#1054 - Unknown column 'lastdate' in 'where clause'
SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
WHERE DATE(MAX(IFNULL(date_lastrun, date_creation))) > "2022-03-01"
but it returns #1111 - Invalid use of group function
Do you have any idea how to accomplish that?
I hope to return the element with the bigger date compared to a specific date.
Do not use the MAX in the WHERE clause but limit the result to dates bigger than "2022-03-01" and then get the biggest one.
SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate FROM
processes WHERE DATE(IFNULL(date_lastrun, date_creation)) >
"2022-03-01";
I would prefer GREATEST with COALESCE here:
SELECT id, GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) AS lastdate
FROM processes
WHERE GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) > "2022-03-01";
MAX is unhandy in this situation due to its limitation to one argument, see also this article: difference max <-> greatest
COALESCE is required in this case because GREATEST is not able to deal with NULL values in MYSQL.
Try out: db<>fiddle

Calculate Sum of Mean and Std dev in sql query on single column

I am having table name as "Table1" in mysql.I have to find Sum of Mean and Std dev on column "Open".I did it easily using python but I am unable to do it using sql.
Select * from BANKNIFTY_cal_spread;
Date Current Next difference
2021-09-03 00:00:00 36914.8 37043.95 129.14999999999418
2021-09-06 00:00:00 36734 36869.15 135.15000000000146
2021-09-07 00:00:00 36572.9 36710.65 137.75
2021-09-08 00:00:00 36945 37065 120
2021-09-09 00:00:00 36770 36895.1 125.09999999999854
Python Code-
nf_fut_mean = round(df['difference'].mean())
print(f"NF Future Mean: {nf_fut_mean}")
nf_fut_std = round(df['difference'].std())
print(f"NF Future Standard Deviation: {nf_fut_std}")
upper_range = round((nf_fut_mean + nf_fut_std))
lower_range = round((nf_fut_mean - nf_fut_std))
I search for Sql solution but I didn't get it. I tried building query but it's not showing correct results in query builder in grafana alerting.
Now I added Mean column ,std dev column , upper_range and lower_range column using python dataframe and pushed to mysql table.
#Booboo,
After removing Date from SQL Query, it's showing correct results in two columns- average + std_deviation and average - std_deviation.
select average + std_deviation, average - std_deviation from (
select avg(difference) as average, stddev_pop(difference) as std_deviation from BANKNIFTY_cal_spread
) sq
It looks as though the sample you're using for the aggregations for MEAN, STDDEV, etc is the entire table - in which case you have to drop the DATE field from the query's result set.
You could also establish the baseline query using a CTE (Common Table Expression) using a WITH statement instead of a subquery, and then apply the subsequent processing:
WITH BN_CTE AS
(
select avg(difference) as average, stddev_pop(difference) as std_deviation from BANKNIFTY_cal_spread
)
select average + std_deviation, average - std_deviation from BN_CTE;
With the data you posted having only a single Open column value for any given Date column value, you standard deviation should be 0 (and the average just that single value).
I am having difficulty in understanding your SQL since I cannot see how it relates to finding the sum (and presumably the difference, which you also seem to want) of the average and standard deviation of column Open in table Table1. If I just go by your English-language description of what you are trying to do and your definition of table Table1, then the following should work. Note that since we want both the sum and difference of two values, which are not trivial to calculate, we should calculate those two values only once:
select Date, average + std_deviation, average - std_deviation from (
select Date, avg(Open) as average, stddev_pop(Open) as std_deviation from Table1
group by Date
) sq
order by Date
Note that I am using column aliases in the subquery that do not conflict with built-in MySQL function names.
SQL does not allow both calculating something in the SELECT clause and using it. (Yes, #variables allow in limited cases; but that won't work for aggregates in the way hinted in the Question.)
Either repeat the expressions:
SELECT average(difference) AS mean,
average(difference) + stddev_pop(difference) AS "mean-sigma",
average(difference) - stddev_pop(difference) AS "mean+sigma"
FROM BANKNIFTY_cal_spread;
Or use a subquery to call the functions only once:
SELECT mean, mean-sigma, mean+sigma
FROM ( SELECT
average(difference) AS mean,
stddev_pop(difference) AS sigma
FROM BANKNIFTY_cal_spread
) AS x;
I expect the timings to be similar.
And, as already mentioned, avoid using aliases that are identical to function names, etc.

smallest value between difference of two columns mysql

please, I want to select from mysql tables where the absolute difference between two columns is the smallest value between the absolute difference values.
I tried this syntax but it was not right
SELECT strike FROM options_20161230 ORDER BY ask - bid ASC LIMIT 1
I wonder if I can create a new column in the table as the difference between two columns, is that possible?
also I want to select where one column has a value between two numbers, I tried this
SELECT strike FROM options_20161230 WHERE 7 < Expiration - Datadate < 37 AND type ='put' AND UnderlyingSymbol = 'SPY'
it works when limited Expiration - Datadate by one value < 37. however It was not working with two values <,> ?
any idea please!
Many Thanks
Your first query is close. You just want abs():
SELECT strike
FROM options_20161230
ORDER BY abs(ask - bid) ASC
LIMIT 1;
Your third query should use between (assuming the difference is an integer) or two inequalities:
SELECT strike
FROM options_20161230
WHERE Expiration - Datadate BETWEEN 8 AND 36 AND
type ='put' AND
UnderlyingSymbol = 'SPY';

(MySql) select query returns empty row in WHERE and AND condition

I have two related table,a one to many relations.I can display values on a selected column in where condition
What is the correct way when adding 'AND' clause in the above query?I tried this queries but it result empty set.
The values in date_created all include a time component 08:00:00. However, you are comparing it as equal to the date value '2014-03-13' which implies 2014-03-12 00:00:00, and is therefore not equal to 2014-03-12 08:00:00
To make that comparison the way you are attempting, you need to truncate the value in date_created to only the date portion, removing the time with MySQL's native DATE() function.
SELECT date_created
FROM collections
WHERE
-- Truncate the datetime to a date only
DATE(date_created) = '2014-03-12'
AND loan_id = 3942
The above example is that of your first query attempt, but using the JOIN requires the same solution in the WHERE clause.
I found a solution to my problem. I change my query into
SELECT
date_created
FROM collections
WHERE DATE(date_created) = '2014-03-12' AND loan_id = 3942;
Now it returns rows with the specific dates.

MySQL - Select most recent date out of a set of several possible timestamps?

I would like to know if this is possible using a mysql query:
I have a table called updates.
In the updates table I have 2 columns, id and timestamp.
I have 5 rows each with the same id but with different date timestamps. An example of this timestamp would be the value: 2012-08-04 23:14:09.
I would like to select only the most recent timestamp value out of the 5 results. This could also be explained by saying that I would like to select the value that is closest to the current date and time. How could I do this?
SELECT id, timestamp FROM updates ORDER BY timestamp DESC LIMIT 1
have you tried SELECT MAX(timestamp) ?