Difference between table row values in the same - sqlite

I have a SQLite table:
CREATE TABLE `Readings` ( `ID` TEXT, `Reading` TEXT, `Date` TEXT )
Every Date I have real Readings from different sensors identified by IDs. Is it possible to get a result table with differences between Readings from sensors with the same ID but for different Dates?

Assuming that you are using a proper date format, you can look up the corresponding previous value with a correlated subquery:
SELECT ID,
Date,
Reading - (SELECT Reading
FROM Readings AS R2
WHERE R2.ID = Readings.ID
AND R2.Date < Readings.Date
ORDER BY Date DESC
LIMIT 1
) AS Difference
FROM Readings;

Related

Count by minute in Riak TS

I'm trying to grasp the recently added group by in Riak TS.
I'm unable to find a way to group my results by minute, e.g. count. I'll show an example below.
CREATE TABLE Results
(
result VARCHAR NOT NULL,
time TIMESTAMP NOT NULL,
PRIMARY KEY (
(QUANTUM(time, 1, 'm')),
time
)
)
Inserts
INSERT INTO FreightMinuteResult VALUES ('Novo', '2017-12-07 12:03:45Z');
INSERT INTO FreightMinuteResult VALUES ('Novo', '2017-12-07 12:04:45Z');
INSERT INTO FreightMinuteResult VALUES ('Novo', '2017-12-07 12:05:45Z');
INSERT INTO FreightMinuteResult VALUES ('Novo', '2017-12-07 12:05:46Z');
Query
select count(*) from FreightMinuteResult where time > '2017-12-07 12:01:00Z' and time < '2017-12-07 12:06:00Z' group by time;
The result is
+--------+--------------------+
|COUNT(*)| time |
+--------+--------------------+
| 1 |2017-12-07T12:04:45Z|
| 1 |2017-12-07T12:03:45Z|
| 1 |2017-12-07T12:05:45Z|
| 1 |2017-12-07T12:05:46Z|
+--------+--------------------+
How to count the number of occurrences per minute using Riak TS?
Thanks.
The quantum is used to organize the data in the backend to streamline query operations, while group by uses the exact value of the specified field. The timestamps 2017-12-07T12:05:45Z and 2017-12-07T12:05:46Z occur in the same minute and will therefore be stored in the same location on disk, but they are still stored as distinct second-resolution timestamp values that will be grouped separately.
If you want to be able to group by the minute you will need to either round the timestamps when inserting, or modify your table to include a minute field that can be grouped.

How do you update an existing date to a random date in a range?

In one of my tables I have datetime field in which the data in the table column is populated with something like "2016-01-07 01:33:00".
What I want to do is change ONLY the date to a random date within a range (ie: 2016-02-01 thru 2016-02-28) without changing the time. The end result might be "2016-02-13 01:33:00".
What mysql command string would accomplish this task?
Something like
UPDATE someTable SET someDate = DATE_ADD(
someDate,
INTERVAL
DATEDIFF(rangeStart, someDate) +
ROUND(RAND()*DATEDIFF(rangeEnd, rangeStart))
DAY
);
where someTable.someDate is your existing data, and rangeStart and rangeEnd are the boundaries of your target date range.
Here you take the initial date, add enough days to it to reach the range start, and then further add a random number of days no greater than the number of days in your target range.
In MsSQL it could be:
select dateadd(day,cast((RAND() * 30) as int),getdate())
Substitute getdate() with your input date.
(RAND() * 30) is used to randomly generate a number of days up to 30.

Compare date columns

I need to retrieve the rows that service_date is greater than prod_date.
The data type for prod_date is VARCHAR(10) (2/20/2014 for example) and the data type for service_date is DATE (YYYYMMDD). If I query service_date using "select service_date from service where service_date ='20140201'", the result is showing "2/1/2014" in the result grid. However, it does not work in the query below when I convert service_date to varchar to compare with prod_date. It pulls out all the rows instead of the ones that have greater service_date.
SELECT P.PROD_ID, P.PROD_DESC, S.PROD_ID, S.SERVICE_LOC
FROM PRODUCT P
INNER JOIN SERVICE S
WHERE P.PROD_ID = S.PROD_ID
AND CAST(S.SERVICE_DATE AS VARCHAR(10)) >= P.PROD_DATE
I suggest you use date ordering instead of string/varchar ordering if possible for simplicity and since its [ probably ] closer to what your interested in and less likely to confuse
For example
'01/02/2014' >= '04/01/2013' -- if these are dates or cast to dates
but
'01/02/2014' < '04/01/2013' -- if these are strings
So to keep things simple, it makes sense to cast PROD_DATE to a date when comparing these two fields like :
SELECT P.PROD_ID, P.PROD_DESC, S.PROD_ID, S.SERVICE_LOC
FROM PRODUCT P
INNER JOIN SERVICE S
WHERE P.PROD_ID = S.PROD_ID
AND S.SERVICE_DATE >= cast(P.PROD_DATE as date format 'DD/MM/YYYY')
;
if theres any doubts on prod_dates quality as valid dates can check the conversion on all dates first ( before running/adjusting above )
This isn't 100% error proof given your date is character and could have unexpected values. It does show how you can append a leading 0 to the month value and cast it to a date when the month is determined to be a single digit based on the location of the / in the second position of the PROD_DATE value for a given row.
SELECT CASE WHEN POSITION('/' IN TRIM(P.PROD_DATE)) = 2
THEN CAST('0'|| TRIM(P.PROD_DATE) AS CHAR(10)) AS DATE FORMAT 'MM/DD/YYYY')
ELSE CAST(P.PROD_DATE AS DATE FORMAT 'MM/DD/YYYY')
END AS PROD_DATE_
FROM PRODUCT P;

Selecting Rows with based on Count (SQLite)

Hoping for some help with this:
1) I am trying to select all calls (rows) for CustomerIDs that show up 6 or more times within a 30 day rolling period, so if the CustomerID is within the file 6 or more times within 30 days, then it would provide me with all records for that CustomerID.
2) I also need to select all calls for CustomerIDs that show up 2 or more times within a 30 day rolling period but ONLY if two certain columns also match (CallType1 and CallType2). Very similar to the query with the 6 calls but we need to consider that the call types are exactly the same too.
SELECT * FROM tablename
WHERE CustomerID IN (SELECT CustomerID FROM tablename
WHERE "CustomerID"
IN ('MyProgram'));
The query above selects all of the CustomerIDs which reach my program. I need to add the logic to count >=6 CustomerIDs (item 1 above) and then a second query to get the >=2 with the same CallTypes.
The innermost subquery computes how many calls there are in the window beginning at First.
The middle subquery checks this value for every possible window in the table. (This is inefficient, but SQLite has no window functions.)
SELECT *
FROM TableName
WHERE CustomerID IN (SELECT CustomerID
FROM TableName AS First
WHERE (SELECT COUNT(*)
FROM TableName
WHERE Date BETWEEN First.Date
AND date(First.Date, '+30 days')
AND CustomerID = First.CustomerID
) >= 6)
This assumes that there is a column Date using the default date format (yyyy-mm-dd).

how to get a average of days with two different tables

There are two tables 1)HR_OrderRequest (column to be considered is HRdate) other columns are HRUID,UID
2)HR_Supplydetails(colmn to be considered is HRUID) other columns are createddttm,UID
by considering the date from HR_Supplydetails we should find the average days taken for that particular UID time taken to release of HRdate .I have a problem getting a average of days
Please do the need .
You can do a datediff:
SELECT AVG(DATEDIFF(day, createddttm,HRdate))
And then do your join on the two tables.
so the steps would be first getting the number of days for a order so you have like these tables:
order (id, date) # this date is the date the order was placed
supply (id, date) # this date is the date the order was filled
these might not be right but i think they are close
select avg(days)
from (select (supply.date-order.date) as days
from order join supply on order.id=supply.id)
but the sub query isn't needed as it can be written as:
select avg(supply.date-order.date)
from order join supply on order.id=supply.id;
now to map this to your tables:
HR_OrderRequest (HRUID, UID, HRdate)
HR_Supplydetails (HRUID, UID, createddttm)
select avg(HR_OrderRequest.HRdate-HR_Supplydetails.createddttm)
from HR_OrderRequest join HR_Supplydetails on HR_OrderRequest.HRUID=HR_Supplydetails.HRUID
where UID=?
clearly if you have date functions use them

Resources