How to create data table using dynamic dates functions like now() or ago()? - azure-data-explorer

Is there a way to create a data table using dynamic dates function like now() or ago()? I am not sure it's possible or just an issue of finding the right syntax.
Works
let Logs = datatable(timestamp: datetime) [
datetime(2022-12-02 2:00:00.00),
datetime(2022-12-02 6:00:00.00),
];
Does not work
let Logs = datatable(timestamp: datetime) [
now(),
datetime(now()- ago(3h)),
];
Thoughts?

datatable accept only literals (no expressions, no functions).
You can use the union operator with multiple print statements:
union
(print 1, now())
,(print 2, ago(3h))
| project-rename id = print_0, timestamp = print_1
id
timestamp
2
2023-02-15T05:29:23.2203689Z
1
2023-02-15T08:29:23.2203689Z
Fiddle
P.S.
datetime(now()- ago(3h)) is wrong.
datetime accept only literal.
now() - ago(3h) is equal to 3h.
Use ago(3h) or now() - 3h

Related

Retrive date wise data from SQLITE database kotlin

I have one SQlite database where i store some data with date.
Now i want to get data date wise like:
Month wise - it means i pass the value like Current date is EndDate to this month 1st date.
Year wise - it means i want to get data 1st-april-20..previews to 31-march-20..current
Start and End date wise - hear is which i pass date.
For that i got one solution is HERE for java.
But i have no idea this HOW TO WORK. Anyone please explain me how to work this and How to i get data as i mention above. FOR KOTLIN
TABLE
db.createTable(customerDetail, true,
credit_id to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
credit_type to TEXT,
c_id to TEXT,
credit_amount to TEXT,
credit_date to TEXT,
addFrom to TEXT
)
UPDATE
For Month wise data i'll try below query like:
"SELECT * FROM $customerDetail WHERE $credit_date BETWEEN strftime('%d-%m-%Y', '$startDate') AND strftime('%d-%m-%Y', '$currentDate')"
/*SELECT * FROM CustomerDetail WHERE credit_date BETWEEN strftime('%d-%m-%Y', '01/02/2019') AND strftime('%d-%m-%Y', '23/02/2019')*/
But it's give me arralistSize = 0.
After that i can write new query like:
"SELECT * FROM $customerDetail WHERE $credit_date BETWEEN '$startDate' AND '$currentDate'"
/*SELECT * FROM CustomerDetail WHERE credit_date BETWEEN '01/02/2019' AND '23/02/2019'*/
In this query data will return. But it's return all data without any filtering.
If anyone knows why this work like this please help me.
MY DATA LIST
Thanks in advance.
Solution :
Solution for MONTH wise
I just change date format "dd/mm/yyyy" TO "yyyy/mm/dd" and re insert all data.
AND Fire below QUERY :
"SELECT * FROM $customerDetail WHERE $credit_date BETWEEN '$startDate' AND '$currentDate'"
SQLite does not have a Date data type like other RDBMS's. It treats dates as TEXT.
So when it compares the credit_date column it actually does compare strings.
This would be fine if you stored your dates in the format YYYY-MM-DD and compared against the same format.
But if you store your dates in the format DD/MM/YYYY then you can't compare.
So the best solution would be to change the format of the column credit_date to YYYY-MM-DD.
If this is not possible then you have to transform the string value of the column like this:
substr(credit_date, 7, 4) || '-' || substr(credit_date, 4, 2) || '-' || substr(credit_date, 1, 2)
Now you can use this in a query like:
SELECT * FROM $customerDetail
WHERE substr($credit_date, 7, 4) || '-' || substr($credit_date, 4, 2) || '-' || substr($credit_date, 1, 2)
BETWEEN '$startDate' AND '$currentDate'
But you have to make sure that $startDate and $currentDate are also in the format YYYY-MM-DD

Ecto/Elixir, How can I query by date?

I am working on statistics page of my app and trying to query data by date.
To get the date range, I use Calendar.Date
date_range = Date.days_after_until(start_date, end_date, true)
|> Enum.to_list
And it returns date list of dates and each date looks like "2017-04-07". So with the date I got from date_range, I tried to query but it triggers an error like below.
where cannot be cast to type Ecto.DateTime in query: from o in Myapp.Order,
where: o.created_date >= ^~D[2017-04-07]
For created_date field of Order, I made field like this,
field :created_date, Ecto.DateTime.
If I want to query by date, how can I query it?
Thank in advance.
It looks like you're trying to compare a date and datetime. You need to cast one of them to the other type so the comparison works, e.g. convert the datetime in the database to a date:
date = ~D[2017-01-01]
from p in Post, where: fragment("?::date", p.inserted_at) >= ^date
or convert the Elixir Date to NaiveDateTime:
{:ok, datetime} = NaiveDateTime.new(date, ~T[00:00:00])
from p in Post, where: p.inserted_at >= ^datetime
If you have a start and end date, you just need to add an and to either. You don't need to generate the whole list of dates using any library.
from p in Post,
where: fragment("?::date", p.inserted_at) >= ^start_date and
fragment("?::date", p.inserted_at) <= ^end_date
or
from p in Post,
where: p.inserted_at >= ^start_datetime and
p.inserted_at <= ^end_datetime

Reformat dates in column

I have some data in an SQLite DB of the form:
id column1 date
111 280 1/1/2014
114 275 1/2/2014
The date field is of type TEXT. I've been made aware (https://www.sqlite.org/lang_datefunc.html) that I should have the dates formatted like YYYY-MM-DD to take advantage of SQLite's datetime functionality. Is there a query I could run to change the format from
mm/dd/yyyy
to
YYYY-MM-DD
in place?
Your current date format has four possible forms:
m/d/yyyy
m/dd/yyyy
mm/d/yyyy
mm/dd/yyyy
To rearrange the fields, extract them with substr() and then combine them again.
It might be possible to determine the positions of the slashes with instr(), but for a one-off conversion, just using four queries is simpler:
UPDATE MyTable
SET date = substr(date, 6, 4) || '-' ||
substr(date, 1, 2) || '-' || '0' ||
substr(date, 4, 1)
WHERE date LIKE '__/_/____';
-- this is mm/d/yyyy; similarly for the other forms, modify positions and zeros
Without any frills such as exception handling!
This approach is slightly simpler because strptime doesn't mind about presence or absence of leading zeroes in days and months.
>>> from datetime import datetime
>>> import sqlite3
>>> con = sqlite3.connect(':memory:')
>>> cur = con.cursor()
>>> cur.execute('CREATE TABLE EXAMPLE (date_column text)')
<sqlite3.Cursor object at 0x00000000038D07A0>
>>> cur.execute('INSERT INTO EXAMPLE VALUES ("1/1/2014")')
<sqlite3.Cursor object at 0x00000000038D07A0>
>>> def transformDate(aDate):
... tempDate = datetime.strptime(aDate, '%d/%m/%Y')
... return tempDate.strftime('%Y-%m-%d')
...
>>> transformDate('1/1/2014')
'2014-01-01'
>>> con.create_function('transformDate', 1, transformDate)
>>> cur.execute('UPDATE EXAMPLE SET date_column = transformDate(date_column)')
<sqlite3.Cursor object at 0x00000000038D07A0>

Evaluating string/combination of variables as logical expression in oracle pl/sql

In my Pl/Sql code , I have three variables v_var1 , v_operand , v_var2 whose values are populated based on some logic (v_var1 & v_var2 can be date , number , varchar. Associated Operand will be according to data type only). A sample would be
v_var1 = 10 , v_operand = '=' , v_var2 = 20.
Based on these value , I have to evaluate whether the condition "v_var1 -v_operand- v_var2"is true or false.
Ex :- with above values, I have to evaluate whether 10 equals 20 or not.
How can I achieve this ? Can I pass the whole string as '10 = 20' to some function and get the result as false?
One way I can think of is to write CASE statements for evaluating but can there be a better way ?
You could use dynamic SQL to do the evaluation as a filter on the dual table:
declare
v_var1 varchar2(10) := '10';
v_operand varchar2(10) := '=';
v_var2 varchar2(10) := '20';
l_result number;
begin
execute immediate 'select count(*) from dual where :var1 ' || v_operand || ' :var2'
into l_result using v_var1, v_var2;
if l_result = 1 then
dbms_output.put_line('True');
else
dbms_output.put_line('False');
end if;
end;
/
PL/SQL procedure successfully completed.
False
If the condition is true the count will get 1, otherwise it will get 0, and you can then test that via the local variable you select the count into.
Holding dates and numbers as strings isn't ideal, even temporarily, but might be OK as long as you convert to/from the real data types consistently, e.g. always explicitly converting dates with to_date and to_char and specifying the format masks.

Updating table in Oracle

I have a table in Oracle call STATISTICS.
COLUMN NAME DATE TYPE
MODEL VARCHAR2(30 BYTE)
NEW_COUNT NUMBER
NEW_DATE DATE
OLD_COUNT NUMBER
OLD_DATE DATE
PRNCT_CHANGE NUMBER
Now I have sql that updates statistics table:
UPDATE STATISTICS
SET
OLD_COUNT = NEW_COUNT,
NEW_COUNT =
( -- semantic table --
SELECT COUNT(*)
FROM TABLE(SEM_MATCH(
'{
?s ?p ?o
}',
SEM_Models(MODEL),NULL,
SEM_ALIASES(SEM_ALIAS('','http://SEMANTIC#')),NULL))
),
OLD_DATE = NEW_DATE,
NEW_DATE = SYSDATE
WHERE MODEL = &MY_MODEL
;
Now, can I do this? Push the date from a new date to an old date before I update the new date?
I am also doing the same thing with the NEW_COUNT and OLD_COUNT...
It sounded logical but is ok to do this?
So I followed my own advice :) and it worked just fine. I am not sure if this is the best practice but it does the trick

Resources