smallest value between difference of two columns mysql - 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';

Related

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

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

Sql search Result between two dates

i have a table name expected expense in which i have 4 columns name Expense_title, Amount, expense_category, date and all the 4 columns have var char type. When I try to find expense between two dates it work fine for same year, e.g. 11/27/2018 and 12/27/2018, but it doesn't get any result when I try to find expense between two years, e.g. 12/27/2018 And 01/27/2019. please help
I am trying this query
SELECT *
from expected_expense
WHERE Date BETWEEN '$start_date' AND '$end_date'
As per the comments, this is because of the varchar type.
The between operator is nothing different than doing two closed inequalities for its range limits. In your example,
between 12/27/2018 And 01/27/2019
will be changed internally to
>= 12/27/2018 and <= 01/27/2019
but these are not dates, they are text. And the second one is less than the first, so nothing will be returned. It's like asking the question: which letter comes after q but before b? None.
Either change the fields to datetime, or use conversion functions in your query.

how can I calculate the SUM in 4days buckets over all dates

I have a MySQL DB where one column is the DATE and the other column is the SIGNAL. Now I would like to calculate the SUM over Signal for 4 days each.
f.e.
SUM(signal over DATE1,DATE2,DATE3,DATE4)
SUM(signal over DATE5,DATE6,DATE7,DATE8)
...
whereas Date_N = successor of DATE_N-1 but need not to be the day before
Moreless the algo should be variable in the days group. 4 ist just an example.
Can anyone here give me an advice how to perform this in MySQL?
I have found this here group by with count, maybe this could be helpful for my issue?
Thanks
Edit: One important note: My date ranges have gaps in it. you see this in the picture below, in the column count(DISTINCT(TradeDate)). It should be always 4 when I have no gaps. But I DO have gaps. But when I sort the date descending, I would like to group the dates together always 4 days, f.e. Group1: 2017-08-22 + 2017-08-21 + 2017-08-20 + 2017-08-19, Group2: 2017-08-18 + 2017-08-17+2017-08-15+2017-08-14, ...
maybe I could map the decending dateranges into a decending integer autoincrement number, then I would have a number without gaps. number1="2017-08-17" number2="2017-08-15" and so on ..
Edit2:
As I see the result from my table with this Query: I might I have double entries for one and the same date. How Can I distinct this date-doubles into only one reprensentative?
SELECT SUM(CondN1),count(id),count(DISTINCT(TradeDate)),min(TradeDate),max(TradeDate) ,min(TO_DAYS(DATE(TradeDate))),id FROM marketstat where Stockplace like '%' GROUP BY TO_DAYS(DATE(TradeDate)) DIV 4 order by TO_DAYS(DATE(TradeDate))
SUM() is a grouping function, so you need to GROUP BY something. That something should change only every four days. Let's start by grouping by one day:
SELECT SUM(signal)
FROM tableName
GROUP BY date
date should really be of type DATE, like you mentioned, not DATETIME or anything else. You could use DATE(date) to convert other date types to dates. Now we need to group by four dates:
SELECT SUM(signal)
FROM tableName
GROUP BY TO_DAYS(date) DIV 4
Note that this will create an arbitary group of four days, if you want control over that you can add a term like this:
SELECT SUM(signal)
FROM tableName
GROUP BY (TO_DAYS(date)+2) DIV 4
In the meantime and with help of KIKO I have found the solution:
I make a temp table with
CREATE TEMPORARY TABLE if not EXISTS tradedatemaptmp (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY) SELECT Tradedate AS Tradedate, CondN1, CondN2 FROM marketstat WHERE marketstat.Stockplace like 'US' GROUP BY TradeDate ORDER BY TradeDate asc;
and use instead the originate tradedate the now created id in the temp table. So I could manage that - even when I have gaps in the tradedate range, the id in the tmp table has no gaps. And with this I can DIV 4 and get the always the corresponding 4 dates together.

Getting record if any of the value matching on condition in mysql

Here is my table info,
__test
id points date
1 -50 30.09.2013
2 100 2.10.2013
3 100 3.10.2013
4 200 4.10.2013
From this i need to select records,if any of the value contains minus points based on the date
For ex:
select *
from #__test
where date between 30.09.2013 to 3.10.2013
Mentioned query is common for getting in between records fro two dates.But i need the records between two dates,if any of the value contains minus points.
How can i do this ? Kindly help me.
I think this is what you are after:
SELECT *
FROM #__test t
WHERE t.Date BETWEEN '20130930' AND '20131003'
AND EXISTS
( SELECT 1
FROM #__test t2
WHERE t2.Date BETWEEN '20130930' AND '20131003'
AND t2.points < 0
);
It simply checks for the existance of a negative value in the date range and then returns all records for that date range if one is found.
N.B This article is probably worth a read regarding using BETWEEN for date ranges, and there is further reading on date range queries in another article written by Aaron Bertrand

subtract the data for every 5 minutes between two particular times

I have some problem with MYSQL,I need to subtract the data between two particular times,for every 5 minutes and then average it the 5 minutes data.
What I am doing now is:
select (avg(columnname)),convert((min(datetime) div 500)*500, datetime) + INTERVAL 5 minute as endOfInterval
from Databasename.Tablename
where datetime BETWEEN '2012-09-12 10:50:00' AND '2012-09-12 14:50:00'
group by datetime div 500;
It is the cumulative average.
Suppose i get 500 at 11 o' clock and 700 at 11.05 ,the average i need is (700-500)/5 = 40.
But now i am getting (500+700)/5 = 240.
I dont need the cumulative average .
Kindly help me.
For the kind of average you're talking about, you don't want to aggregate multiple rows using a GROUP BY clause. INstead, you want to compute your result using exactly two diffrent rows from the same table. This calls for a self-join:
SELECT (b.columnname - a.columnname)/5, a.datetime, b.datetime
FROM Database.Tablename a, Database.Tablename b
WHERE b.datetime = a.datetime + INTERVAL 5 MINUTE
AND a.datetime BETWEEN '2012-09-12 10:50:00' AND '2012-09-12 14:45:00'
a and b refer to two different rows of the same table. The WHERE clause ensures that they are exactly 5 minutes apart.
If there is no second column matching that temporal distance, no resulting row will be included in the query result. If your table doesn't have data points exactly every five minutes, but you have to search for the suitable partner instead, then things become much more difficult. This answer might perhaps be adjusted for that use case. Or you might implement this at the application level, instead of on the database server.