Query between dates in SQLITE - sqlite

I'm trying to query what happened between today and yesterday. To example on the 17th of June 2016 it would look like:
SELECT * FROM Inspection_Log WHERE date_time BETWEEN '2016-6-16' AND '2016-6-17'
But these days are relative, and this won't work say tomorrow, or really every again. So I've encountered this page where tells me now to use DATE as it's just a polite wrapper around strftime.
But here is my current issue:
This query works:
>SELECT COUNT(*) FROM Inspection_Log WHERE date_time BETWEEN '2016-6-16' AND '2016-6-17'
535
But when I use date('yada', '+1 day')
>SELECT COUNT(*) FROM Inspection_LOG WHERE date_time BETWEEN '2016-6-16' AND DATE('2016-6-16','+1 day')
0
So I try with strftime
>SELECT COUNT(*) FROM Inspection_LOG WHERE date_time BETWEEN '2016-6-16' AND strftime('%Y-%M-%D','2016-6-16','+1 day')
0
So I try with datetime
>SELECT COUNT(*) FROM Inspection_LOG WHERE date_time BETWEEN '2016-6-16' AND datetime('2016-6-16','+1 day')
0
Digging into this here is what i see
SELECT time('now')
'2016-06-24'
SELECT date('now')
'2016-06-24'
SELECT date('now','-1 day')
'2016-06-23'
SELECT date('2016-6-24','-1 day')
NONE
What am I doing wrong?

You need to change: AND strftime('%Y-%M-%D','2016-6-16','+1 day') for AND strftime('%Y-%m-%d','2016-06-16','+1 day').
1 - You should use '%Y-%m-%d' for the first parameter 'YYYY-MM-DD'.
The format string supports the most common substitutions found in the strftime() function from the standard C library plus two new substitutions, %f and %J. The complete list link
2 - A time string must be follow the format: YYYY-MM-DD, then you need to use '2016-06-16'.
There is a question and answer : SQL Select between dates

Okay so I was totally and completely wrong.
My scheme looks like this:
CREATE TABLE InspectionLog(
date_time DATE,
station_name TEXT,
inspection TEXT,
barcode_part_number TEXT,
bus_part_number TEXT,
barcode_serial_number TEXT,
bus_serial_number TEXT,
rework_operation TEXT,
status TEXT,
ng_description TEXT
)
DATE is not a valid data type. It is actually a high level wrapper around INTEGER and TEXT depending on the data placed into it. Sqlite3 defaults to TEXT.
What this means is when I perform an insert/update which does something similar to:
date_time = '2016-6-16'
This is valid as date_time is really TEXT not DATE. And when I preform a search that uses the DATE data type, it will skip any row which isn't a DATE.
The long version is. I inserted ~250MB incorrectly formatted into this table. After fixing my tests and functions so my inserts always have 2 day/month digits the majority of the OP's time queries work correctly.

Related

Sqlite SELECT * for Last 30 days

I have a SQLite DB with the following columns:
File, Date_created, Owner
How do I get the list of files created in the last 30 days?
I tried the following, but it didn't limit the result. The list came back with files created 2 years ago!
SELECT * FROM Table1 WHERE Date_created > (SELECT DATETIME('now', '-30 day'))
Also, not sure if it matters, but my Created_date column is in the following date format: dd/mm/yyyy hh:mm:ss
SQLite doesn't have a native datetime data type, so that comparison's going to be on text. If your records are in DD/MM/YYYY format, you'll end up with comparisons like "07/03/2020" > "2020-06-07" which make little sense.
If you opt to store your datetimes as text, you must use a format that's lexicographically orderable. A great standard format that exhibits this property (if every piece of data has the same timezone, anyway) is ISO 8601, e.g. 2020-07-07 15:04:14+0300 at the time of writing in my timezone. As an aside, even xkcd recommends ISO 8601.
If you opt to store your datetimes as numbers, you can store them as either UNIX time, or maybe, if you're feeling adventurous, as e.g. the number 20200707150414. Do remember neither of these numeric options store timezone information, if that's important to your application.
As an aside,
SELECT * FROM Table1 WHERE Date_created > DATETIME('now', '-30 day')
is enough :)
Something like this might be what you are looking for, it's something that's come up in my head, haven't tested it.
Basically you're going 30 days backwards by Date_created.
SELECT * FROM Table1
WHERE DATEDIFF(DAY, DATEADD(DAY, -30, GETDATE()), Date_created) > 0

I am having a problem with this date format change

I need help with this Teradata date format change
I have tried multiple queries and date formats and nothing seems to work
This was what I tried originally:
'''Teradata
select distinct concat(trim(EXTRACT(month FROM(rqst.admt_dt))), '/1/', trim(EXTRACT(year FROM(rqst.admt_dt)))) as MonYr
'''
When I create a volatile table with this it makes the datatype varchar(25) and I want the datatype as a date. I tried multiple cast date formats but none of the code was accurate. I decided to do this instead:
'''Teradata
select distinct rqst.admt_dt as MonYr
'''
After I run through all my scripts I end up with the final table and the MonYr is a date but I need to change any days that are not 01 to 01. Examples of the dates I end up with are:
6/02/2018
6/15/2018
6/22/2018
I tried this code to modify the DD to 01
'''Teradata
update dl_aa_tm_oprpt_s.TinaPAVDrop
set monyr = date format 'mm/01/yyyy'
'''
That does not work either. I am at a loss as to how to remedy this issue
If you want take a date and get the first day of that month:
SELECT
current_date - extract(day from current_date) + 1
Just replace current_date with your date column.

BigQuery - Get timezone offset from timezone name

Is there any way in BigQuery to get the current UTC timezone offset from a timezone name? For example using the input:
`Australia/Victoria`
How could I currently return:
+10:00
Below example for BigQuery STandard SQL
#standardSQL
WITH `project.dataset.table` AS (
SELECT 'Australia/Victoria' tz_string
)
SELECT tz_string, DATETIME_DIFF(CURRENT_DATETIME(tz_string), CURRENT_DATETIME(), hour) tz_hours
FROM `project.dataset.table`
with result
Row tz_string tz_hours
1 Australia/Victoria 10
Another way to do this is to use the (at least, now) built in FORMAT_TIMESTAMP() function and the %Ez format element.
SELECT FORMAT_TIMESTAMP('%Ez', CURRENT_TIMESTAMP(), 'Australia/Victoria');
Result:
+11:00

I need a sqlite equivalent of the folling msaccess query

Select distinct Format(DateAdd(""s""," & columnname & ",""1/1/1980 12:00:00 AM""), 'dd-MMM-yyyy') as A
I have assumed that the seconds to add and the original date are hard coded values below whilst awaiting clarifications requested in the comments.
To add a number of seconds to a date you can use:
select datetime('1980-01-01 00:00:00', "345000 seconds");
This gives the result: 1980-01-04 23:50:00
The example above is just under 4 days in seconds, if you want to truncate the result to just the date as implied by the query in your questions then you can wrap this inside a date function. However, this would give the result in the format "YYYY-MM-DD" rather than "DD-MMM-YYYY" as your access query does.
Unfortunately I cannot find any native SQLite function to convert a numeric month value to mmm format. You can do this manually with replace (similar to the answer to this question), but this is a bit messy.
If you are happy to live with the numeric months then you can simply use:
select strftime('%d-%m-%Y', '1980-01-01 00:00:00', "345000 seconds");
This gives the result: 04-01-1980
More information on the SQLite date / time functions can be found here.

get week number from date into dropdownlist

I have a database table containing a row of dates in DateTime format. what I need to do is get all the distinct weeks numbers of the available dates. for example if I have the following dates:
03-JAN-13
04-JAN-13
09-JAN-13
the sql query would give me the following weeks numbers: 1 and 2.
PS: afterwards I will put these values in a dropdownlist (no problem with that step).
So can anybody tell me how to do it?
You did not specify what RDBMS you are using but you could use the following to get week numbers.
SQL Server you would use DatePart():
select distinct datepart(week, dates) WeekNo
from yourtable
See SQL Fiddle with Demo
In MySQL you could use Week():
select distinct week(dates)
from yourtable
See SQL Fiddle with Demo
In Oracle, you could use to_char():
select distinct to_char(dates, 'W') WeekNo
from yourtable
See SQL Fiddle with Demo
In PostgreSQL you can use the following:
select distinct extract(WEEK from dates) WeekNO
from yourtable
See SQL Fiddle with Demo
Replace the yourtable with your table name and dates with your date column.
Edit #1: If you are using MS Access then you can still use DatePart() (this was tested in MS Access 2003):
SELECT distinct datepart("ww", dates) as WeekNo
FROM yourtable;
In your on load event, or wherever you want, you will put this VBA code
Me!myCombo.RowSource = "yourquerytexthere;"
(Or whatever query you go with..probably whichever one you're using from your last question that Remou answered for you).
I think in this question, you already know what you want to query, you are just asking about setting the control.
That code is just
Me!myCombo.RowSource = "yourquerystring"
like
Me!myCombo.RowSource = "SELECT distinct datepart("ww", dates) FROM yourtable;"
Where Me!myCombo is the name of your combobox.
Annual ISO week# table - Oracle SQL query:
-- ISO_WK# --
SELECT mydate
, TRUNC(mydate, 'w') wk_starts
, TRUNC(mydate, 'w') + 7 - 1/86400 wk_ends
, TO_NUMBER (TO_CHAR (mydate, 'IW')) ISO_WK#
FROM
(
SELECT TRUNC(SYSDATE, 'YEAR')-1 + LEVEL AS mydate
FROM dual
CONNECT BY LEVEL <=
(-- First day of curr year - first day of past year --
SELECT TRUNC(SYSDATE, 'YEAR')-TRUNC(ADD_MONTHS (SYSDATE, -12), 'YEAR') "Num of Days"
FROM dual
)
)
/

Resources