SQLite - add days to a certain date in insert - sqlite

I am using SQLite.
Let's say I have a table like this one:
CREATE TABLE dates (
date1 DATE NOT NULL PRIMARY KEY,
date2 DATE NOT NULL
);
Now, I want date1 to be a certain date and date2 to be date1 + 10 days.
How can I insert values to the table by using only date1 to produce both of them?
only thing i could find on the internet was something like that, but it's obviously not working, except for the case that I replace date('date1',+10days)) with date('now',+10days), but this is not what I want:
insert into dates values('2012-01-01', date('date1','+10 days'))
Any ideas?

Raise a trigger to automatically insert date2 every time you insert a date1 into the table.
CREATE TRIGGER date2_trigger AFTER INSERT ON dates
BEGIN
UPDATE dates SET date2 = DATE(NEW.date1, '+10 days') WHERE date1 = NEW.date1;
END;
-- insert date1 like so; date2 will be set automatically.
INSERT INTO dates(date1) VALUES('2012-01-01');

Instead of INSERT...VALUES use INSERT...SELECT like this:
insert into dates (date1, date2)
select t.date1, date(t.date1, '+10 days')
from (
select '2012-01-01' as date1
union all
select '2012-01-02'
union all
....................
) t
See the demo.
Results:
| date1 | date2 |
| ---------- | ---------- |
| 2012-01-01 | 2012-01-11 |
| 2012-01-02 | 2012-01-12 |

Related

SQL: grouping to have exact rows

Let's say there is a schema:
|date|value|
DBMS is SQLite.
I want to get N groups and calculate AVG(value) for each of them.
Sample:
2020-01-01 10:00|2.0
2020-01-01 11:00|2.0
2020-01-01 12:00|3.0
2020-01-01 13:00|10.0
2020-01-01 14:00|2.0
2020-01-01 15:00|3.0
2020-01-01 16:00|11.0
2020-01-01 17:00|2.0
2020-01-01 18:00|3.0
Result (N=3):
2020-01-01 11:00|7.0/3
2020-01-01 14:00|15.0/3
2020-01-01 17:00|16.0/3
I need to use a windowing function, like NTILE, but it seems NTILE is not usable after GROUP BY. It can create buckets, but then how can I use these buckets for aggregation?
SELECT
/*AVG(*/value/*)*/,
NTILE (3) OVER (ORDER BY date) bucket
FROM
test
/*GROUP BY bucket*/
/*GROUP BY NTILE (3) OVER (ORDER BY date) bucket*/
Also dropped the test data and this query into DBFiddle.
You can use NTILE() window function to create the groups and aggregate:
SELECT
DATETIME(MIN(DATE), ((STRFTIME('%s', MAX(DATE)) - STRFTIME('%s', MIN(DATE))) / 2) || ' second') date,
ROUND(AVG(value), 2) avg_value
FROM (
SELECT *, NTILE(3) OVER (ORDER BY date) grp
FROM test
)
GROUP BY grp;
To change the number of rows in each bucket, you must change the number 3 inside the parentheses of NTILE().
See the demo.
Results:
| date | avg_value |
| ------------------- | --------- |
| 2020-01-01 11:00:00 | 2.33 |
| 2020-01-01 14:00:00 | 5 |
| 2020-01-01 17:00:00 | 5.33 |
I need to use a windowing function, like NTILE, but it seems NTILE is not usable after GROUP BY. It can create buckets, but then how can I use these buckets for aggregation?
You first use NTILE to assign bucket numbers in a subquery, then group by it in an outer query.
Using sub-query
SELECT bucket
, AVG(value) AS avg_value
FROM ( SELECT value
, NTILE(3) OVER ( ORDER BY date ) AS bucket
FROM test
) x
GROUP BY bucket
ORDER BY bucket
Using WITH clause
WITH x AS (
SELECT date
, value
, NTILE(3) OVER ( ORDER BY date ) AS bucket
FROM test
)
SELECT bucket
, COUNT(*) AS bucket_size
, MIN(date) AS from_date
, MAX(date) AS to_date
, MIN(value) AS min_value
, AVG(value) AS avg_value
, MAX(value) AS max_value
, SUM(value) AS sum_value
FROM x
GROUP BY bucket
ORDER BY bucket

SQLite: Calculate how a counter has increased in current day and week

I have a SQLite database with a counter and timestamp in unixtime as showed below:
+---------+------------+
| counter | timestamp |
+---------+------------+
| | 1582933500 |
| 1 | |
+---------+------------+
| 2 | 1582933800 |
+---------+------------+
| ... | ... |
+---------+------------+
I would like to calculate how 'counter' has increased in current day and current week.
It is possible in a SQLite query?
Thanks!
Provided you have SQLite version >= 3.25.0 the SQLite window functions will help you achieve this.
Using the LAG function to retrieve the value from the previous record - if there is none (which will be the case for the first row) a default value is provided, that is same as current row.
For the purpose of demonstration this code:
SELECT counter, timestamp,
LAG (timestamp, 1, timestamp) OVER (ORDER BY counter) AS previous_timestamp,
(timestamp - LAG (timestamp, 1, timestamp) OVER (ORDER BY counter)) AS diff
FROM your_table
ORDER BY counter ASC
will give this result:
1 1582933500 1582933500 0
2 1582933800 1582933500 300
In a CTE get the min and max timestamp for each day and join it twice to the table:
with cte as (
select date(timestamp, 'unixepoch', 'localtime') day,
min(timestamp) mindate, max(timestamp) maxdate
from tablename
group by day
)
select c.day, t2.counter - t1.counter difference
from cte c
inner join tablename t1 on t1.timestamp = c.mindate
inner join tablename t2 on t2.timestamp = c.maxdate;
With similar code get the results for each week:
with cte as (
select strftime('%W', date(timestamp, 'unixepoch', 'localtime')) week,
min(timestamp) mindate, max(timestamp) maxdate
from tablename
group by week
)
select c.week, t2.counter - t1.counter difference
from cte c
inner join tablename t1 on t1.timestamp = c.mindate
inner join tablename t2 on t2.timestamp = c.maxdate;

How can I fix wrong date format in SQLite

I'm working on app where I use SQLite to store data.
I created column Date. Since I'm beginner I made a mistake by inputing date as %m/%d/%Y (for example: 2/20/2020)
Now I've got a problem while taking out rows between selected dates.
I tried using this code:
SELECT * FROM Table WHERE Date BETWEEN strftime('%m/%d/%Y','2/5/2019') AND strftime('%m/%d/%Y','2/20/2020')
But that's not working.
Example table:
ID | Date
01 | 9/2/2019
02 | 2/20/2020
Thank you in advance for your help.
Update your dates to the only valid for SQLite date format which is YYYY-MM-DD:
update tablename
set date = substr(date, -4) || '-' ||
substr('00' || (date + 0), -2, 2) || '-' ||
substr('00' || (substr(date, instr(date, '/') + 1) + 0), -2, 2);
See the demo.
Results:
| ID | Date |
| --- | ---------- |
| 1 | 2019-09-02 |
| 2 | 2020-02-20 |
Now you can set the conditions like:
Date BETWEEN '2019-02-05' AND '2020-02-20'
If you do this change then you can use the function strftime() in select statements to return the dates in any format that you want:
SELECT strftime('%m/%d/%Y', date) date FROM Table
If you don't change the format of date column then every time you need to compare dates you will have to transform the value with the expression used in the UPDATE statement, and this is the worst choice that you could make.

Select weekend or weekday data from a table based on date param

How can I select data from a table based on weekday or weekend, like
if date is a weekday then select only historical weekday data from the table &
if date is a weekend then select only historical weekend data.
I have tried to do that in this way but no luck
DECLARE #MyDate DATE = '08/17/2013'
SELECT datename(dw,#MyDate)
SELECT * FROM MyTable
WHERE
datename(dw,DateColumnInTable) IN (
CASE WHEN (datename(dw,#MyDate) IN ('Saturday','Sunday')) THEN '''Saturday'',''Sunday'''
ELSE 'Monday'',''Tuesday'',''Wednesday'',''Thursday'',''Friday'
END )
Any I can see lots of data in my table for saturday and sunday but this query is giving me blank record set.
Here's one way:
DECLARE #MyDate DATE = '08/17/2013'
IF (DATEPART(weekday, #MyDate) IN (1,7))
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) IN (1,7)
ELSE
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6
If you would like to do it in one clause you can do something like the following, but it may perform worse:
SELECT *
FROM MyTable
WHERE (DATEPART(weekday, #MyDate) IN (1,7) AND DATEPART(weekday, DateColumnInTable) IN (1,7))
OR (DATEPART(weekday, #MyDate) BETWEEN 2 AND 6 AND DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6)

How to pivot table in SQL

Lab Test Name Source Collected Date Results
Urea 6/4/2013 12:00:00 AM 5
Uric Acid 6/4/2013 12:00:00 AM 10
Cholesterol 6/3/2013 12:00:00 AM 25
I have a datatable with above values.
I need to pivot it to following structure:
Urea Uric Acid Cholesterol
6/4/2013 12:00:00 AM 5 10 -
6/3/2013 12:00:00 AM - - 25
If you look at the answer linked by Mikael, you'll realize that you will need to build the columns for your pivot statement dynamically since the PIVOT syntax doesn't allow a subselect within the FOR clause. So essentially you need to do something like this:
DECLARE
#cols AS NVARCHAR(MAX),
#y AS INT,
#sql AS NVARCHAR(MAX);
-- Construct the column list for the IN clause
-- e.g., [Urea],[Uric Acid],[Cholesterol]
SET #cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT (LabTestName) AS y FROM YourTable) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
You can now build your PIVOT statement as so:
set #SQL = N'
SELECT SourceCollectedDate,'+#cols+N'
FROM YourTable
PIVOT (
SUM(results) FOR LabTestName IN ( '+#cols+N')
) AS PivotTable
ORDER BY SourceCollectedDate desc
'
And execute it:
EXEC sp_executesql #sql
Which will produce:
SourceCollectedDate Urea Uric Acid Cholesterol
2013-06-04 00:00:00.000 5 10 NULL
2013-06-03 00:00:00.000 NULL NULL 25
Just note that my example has YourTable as the table name. You need to replace that with your actual table name.
SQL Fiddle (Based off of what Chad created)
Here's a solution that doesn't require pivot or dynamic SQL. The tradeoff is that you need to specify each possible Lab Test Name in your query.
SELECT [Source Collected Date],
MAX(CASE WHEN [Lab Test Name] = 'Urea'
THEN Results ELSE NULL END) AS Urea,
MAX(CASE WHEN [Lab Test Name] = 'Uric Acid'
THEN Results ELSE NULL END) AS [Uric Acid],
MAX(CASE WHEN [Lab Test Name] = 'Cholesterol'
THEN Results ELSE NULL END) AS Cholesterol
FROM Table1
GROUP BY [Source Collected Date]
See it working here.

Resources