Android Sqlite - Select the row which was inserted 1 hour before - sql

Am working on Android Sqlite where I try to fetch the rows which are inserted 1 hour before.But its not returning any thing,I checked by cursor.count()
I tried with the following queries
String[] columns = new String[] { KEY_ID, KEY_CONTENT1, KEY_CONTENT2,
KEY_CONTENT3, KEY_CONTENT4, KEY_CONTENT5, KEY_CONTENT6};
cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, KEY_CONTENT3 + "< " + "DATETIME('NOW', '-1 hours')", null, null, null, null);
AND another query
String selectRow = "select * FROM detail1 WHERE content3 < DATETIME('NOW', '-1 hours');";
Cursor cursor = sqLiteDatabase.execSQL(selectRow);
AND another query
String selectRow = "select * FROM detail1 WHERE content3 < DATETIME('NOW', '-1 hours');";
cursor = sqLiteDatabase.rawQuery(selectRow,null);
This Query Works for me
String selectRow = "select * FROM detail1 WHERE content3 > DATETIME('NOW', '-1 hours');";
Cursor cursor = sqLiteDatabase.execSQL(selectRow);

DATETIME('NOW', '-1 hours');"
This function returns time in this 2014-01-04,
and in data base 2014-01-04 10:24:21 have in this format. here only 2014 is getting compared not the complete date. better approch i would suggest go with epoch
try below query which will give you difference in terms of seconds
SELECT (strftime('%s','now')/60) - (strftime('%s',content3)/60);

Related

SQL update only values whose value is not already updated

I have a Query it updates the whole tickets in table.
I want it to update only the tickets whose values needs to be updated not update all rows.
e.g.
If slabreachdays is already 10 then new value is also 10 it should not update.
This is my update query.
update ticket
set TICKET.slabreachdays =
FLOOR(((DAYS(TICKET.creationdate) - DAYS(current timestamp)+10)
* 86400 + (MIDNIGHT_SECONDS(TICKET.creationdate) -
MIDNIGHT_SECONDS(current timestamp)))/86400.0)
where TICKET.VENDOR like 'ABC'
and TICKET.STATUS NOT IN('CANCELLED','CLOSED')
This is my select query which selects only the tickets that needs to be updated. This is the query I need to convert to an update query
select * from (
select ticketid,slabreachdays,
FLOOR(((DAYS(TICKET.creationdate) - DAYS(current timestamp)+10) * 86400 + (MIDNIGHT_SECONDS(TICKET.creationdate) - MIDNIGHT_SECONDS(current timestamp)))/86400.0)
as newValue
from ticket
where TICKET.MLOUTSOURCEVENDOR like 'ABC' and TICKET.STATUS NOT IN('CANCELLED','CLOSED'))
where SLABREACHDAYS != newValue
Try it
Where .... And slabeachdays<> aller calculated expression
Try this
update ticket
set TICKET.slabreachdays =
FLOOR(((DAYS(TICKET.creationdate) - DAYS(current timestamp)+10)
* 86400 + (MIDNIGHT_SECONDS(TICKET.creationdate) -
MIDNIGHT_SECONDS(current timestamp)))/86400.0)
where TICKET.VENDOR like 'ABC'
and TICKET.STATUS NOT IN('CANCELLED','CLOSED') and
TICKET.slabreachdays <>
(FLOOR(((DAYS(TICKET.creationdate) - DAYS(current timestamp)+10)
* 86400 + (MIDNIGHT_SECONDS(TICKET.creationdate) -
MIDNIGHT_SECONDS(current timestamp)))/86400.0))

Why does "WHERE (Time_Stamp >= TDateTime-variable)" ignore fractional seconds?

Using Delphi 6 and Microsoft SQL Server 2000.
I need to extract records where a TDateTime Field is > a passed TDateTime, "FromDate".
It fails as if the fractional part of the seconds of the passed TDateTime are always zero.
Debug printouts confirm that the fractions are there.
The WHERE part ignores the fraction part of :Fdate.
Assume the following 3 records:
Record 1: Time_Stamp is 1.2
Record 2: Time_Stamp is 1.4
Record 3: Time_Stamp is 1.6
The value 1.3 is then sent to the Query in :Fdate.
The resulting dataset returns ALL 3 records.
I expected only records 2 and 3 since 1.3 > 1.2
The 'Time_Stamp' field in database is a SQL 'datetime' field.
Everything works perfectly for integer seconds,
i.e. one record per second, or less often, when the decimal fraction is unimportant.
Can anyone point out where my error is?
The SQL statement is generated by code (shown below) as follows:
SELECT TOP 6 * FROM T_TransactionLog
INNER JOIN T_LookUp_TransTypes
ON T_TransactionLog.TransType = T_LookUp_TransTypes.TransType
WHERE (Time_Stamp >= :Fdate)
AND T_TransactionLog.TransType IN (
3,
4,
5
)
AND LockerNo < 60001
ORDER BY Time_Stamp ASC
The code is as follows:
Query.Connection := Sys_DB_Form.ADOConnection;
DataSource.DataSet := Query;
Query.SQL.Add('SELECT TOP ' + IntToStr(cNoTransactions) + ' * FROM
T_TransactionLog');
Query.SQL.Add('INNER JOIN T_LookUp_TransTypes');
Query.SQL.Add('ON T_TransactionLog.TransType =
T_LookUp_TransTypes.TransType');
Query.SQL.Add('WHERE (Time_Stamp ' + S_Condition + ' :Fdate)');
Query.SQL.Add('AND T_TransactionLog.TransType IN (');
Query.SQL.Add(IntToStr(ord(Apl_TrLog.ttEA)) + ',');
Query.SQL.Add(IntToStr(ord(Apl_TrLog.ttMO)) + ',');
Query.SQL.Add(IntToStr(ord(Apl_TrLog.ttMC)));
Query.SQL.Add(')');
Query.SQL.Add('AND LockerNo < ' +
IntToStr(Apl_Config.cLNoOfFirstgate));
if Locker <> 0 then
begin
Query.SQL.Add('AND LockerNo = ' + IntToStr(Locker));
end;
Query.SQL.Add(S_OrderBy);
Query.Parameters.FindParam('Fdate').Value := FromDate; // <<< Fail????
Query.SQL.SaveToFile(GetApplicationDataPath + 'Sql.txt');
try
Query.Open;
except
ShowMessage('Query open fail on ME Show Transaction log');
end;
Please chech the accuracy note for SQL Server datetime and time data types on MSDN
It is written that:
Accuracy Rounded to increments of .000, .003, or .007 seconds
This means
23:59:59.997
is OK
But
23:59:59.998
will be rounded to 23:59:59.997
And
23:59:59.999
will be rounded to 00:00:00 for the next day

Need to convert a numeric field to date in this query

I am running this in sql server but there is an error on the date compare as the column cadodt is a numeric. Is there a quick and easy way to convert that col to numeric? It's date is in YYYYMMDD but I cannot compare against a date field like current date.
select * from openquery(IBSIBM, 'select CABANO, CABCRC, CABCTR, CABCUR, CABKCO, CACLVL, CACOTI,
CACRDT, CACTTP, CADODT, CADOTY, CAEXRT, CAIDNO, CAJONO, CANCRX,
CAPERI, CAREFX, CARSCD, CASCRC, CASCTR, CASTAT, CASTMT, CASYID,
CATIML, CATREF, CATTXT, CATYPC, CAUSER, CAVADT, CAVODT, CAVONO,
CAVOTY ,NANAME from CA1665AFCV.SROCBA,
CA1665AFCV.srolta,
CA1665AFCV.sronam
WHERE CADOTY = ''CHK'' and cajono=ctjono and cadodt = CURRENT DATE()
and caperi=ctperi and caidno=ctidno and ctveno=nanum
and CASTAT = ''Y''')
Assuming cadodt is actually an integer or numeric field and not a character string, try this:
select * from openquery(IBSIBM,
'select CABANO, CABCRC, CABCTR, CABCUR, CABKCO, CACLVL, CACOTI,
CACRDT, CACTTP, CADODT, CADOTY, CAEXRT, CAIDNO, CAJONO, CANCRX,
CAPERI, CAREFX, CARSCD, CASCRC, CASCTR, CASTAT, CASTMT, CASYID,
CATIML, CATREF, CATTXT, CATYPC, CAUSER, CAVADT, CAVODT, CAVONO,
CAVOTY, NANAME
from CA1665AFCV.SROCBA, CA1665AFCV.srolta, CA1665AFCV.sronam
WHERE CADOTY = ''CHK''
and cajono = ctjono
and cadodt = YEAR(CURRENT DATE) * 10000 + MONTH(CURRENT DATE) * 100 + DAY(CURRENT DATE)
and caperi = ctperi
and caidno = ctidno
and ctveno = nanum
and CASTAT = ''Y''')
Aside: I would strongly recommend against using comma joins. The longer ANSI 92 join syntax is much easier to read and maintain. I'd also strongly recommend using qualified column names. This schema is not the easiest to follow as it is. No need to make it even more arcane.
You have these options
convert cadodt from string to date
convert cadodt from intger to date
convert current date to YYYYMMDD string
convert current date to YYYYMMDD integer
1 and 3 assume cadodt is a string
2 and 4 assume cadodt is an intger
3 and 4 are the more efficient approaches as you only change one value.
e.g.
(3) if cadodt is a string in YYYMMDD format:
AND cadodt = VARCHAR_FORMAT(CURRENT DATE, 'YYYYMMDD')
(4) if cadodt is an integer representing YYYYMMDD
AND cadodt = YEAR(CURRENT DATE) * 10000 + MONTH(CURRENT DATE) * 100 + DAY(CURRENT DATE)
the CURRENT DATE() may be causing you some issues use CURRENT_DATE()
Try this:
select * from openquery(IBSIBM, 'select CABANO, CABCRC, CABCTR, CABCUR, CABKCO, CACLVL, CACOTI,
CACRDT, CACTTP, CADODT, CADOTY, CAEXRT, CAIDNO, CAJONO, CANCRX,
CAPERI, CAREFX, CARSCD, CASCRC, CASCTR, CASTAT, CASTMT, CASYID,
CATIML, CATREF, CATTXT, CATYPC, CAUSER, CAVADT, CAVODT, CAVONO,
CAVOTY ,NANAME from CA1665AFCV.SROCBA,
CA1665AFCV.srolta,
CA1665AFCV.sronam
WHERE CADOTY = ''CHK'' and cajono=ctjono and cadodt = CURRENT_DATE()
and caperi=ctperi and caidno=ctidno and ctveno=nanum
and CASTAT = ''Y''')
Replace CADODT = CURRENT DATE() with:
date(substr(char(CADODT), 1, 4) || '-'|| substr(char(CADODT),5, 2) || '-'|| substr(char(CADODT), 7, 2)) = CURRENT DATE
That should convert it from an integer to a date.

Calculate value per day

I have Oracle table where I insert data about network upload and download speed.
CREATE TABLE AGENT_HISTORY(
EVENT_DATE DATE,
NETWORK_UP NUMBER,
NETWORK_DOWN NUMBER
)
I want to generate Bar chart for last 30 days and display total upload traffic per day(24 hours).
select * from AGENT_HISTORY where EVENT_DATE >= SYSDATE - 30;
The problem which I don't know how to solve is how I can calculate the traffic for each day from the column NETWORK_UP. The result of the query should be 30 days with total upload traffic for each day. Is this possible without PL/SQL procedure?
You can do a query like this to aggregate totals data for both the network_up and network_down columns per day.
select trunc(event_day,'day') event_date
,sum(network_up) tot_network_up
,sum(network_down) tot_network_down
from agent_history
where event_day >= trunc(sysdate,'day') - interval '30' day
group by trunc(event_day,'day');
You can do it without embbeding the query in PL/SQL stored code depending on what you use for front end, in java you could you use something like this
Statement stmt = null;
String schema_name = 'abc';
String query = "select trunc(event_day,'day') event_date," +
"sum(network_up) tot_network_up," +
"sum(network_down) tot_network_down " +
"from " + schema_name +".agent_history " +
"where event_day >= trunc(sysdate,'day') " +
"- interval '30' day " +
"group by trunc(event_day,'day')"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String event_data = rs.getString("EVENT_DATE");
int tot_network_up = rs.getInt("TOT_NETWORK_UP");
int tot_network_down= rs.getInt("TOT_NETWORK_DOWN");
.....
}
catch (SQLException e) {
.......
} finally {
......
}
With something like this you just execute pure SQL.
My guess is that you just want to aggregate the data. Something like
SELECT trunc(event_date),
sum(network_up) total_up,
sum(network_down) total_down
FROM agent_history
WHERE event_date >= trunc(sysdate) - 30
GROUP BY trunc(event_date)
If that is not what you want, it would be very helpful to post some sample data, expected output, etc.

SQL Command error ORA-00933 when deal with three tables

Get all vouchers from CRS_T_RES_VOUCHER where IS_OFFLINE_BOOKING is true and (system date - CRS_T_RES_REGISTRATION. UPDATED_DATE) > offline Cancellation Threshold
Offline Cancellation Threshold can be taken from CRS_T_HTL_PARAMETER table.
PARAM_KEY - IBE_OFFLINE_CANCELLATION_THRESHOLD
SELECT v.VOUCHER_NUMBER
FROM CRS_T_RES_VOUCHER v,
CRS_T_RES_REGISTRATION regi,
CRS_T_HTL_PARAMETER para
WHERE v.is_offline_booking = '1'
AND TRUNC (SYSDATE) - TRUNC (v.updated_date) > para.param_value WHERE para.param_key = 'IBE_OFFLINE_CANCELLATION_THRESHOLD'
I encounter ORA-00933: SQL command not properly ended
I got it
need to deal with nested query
SELECT v.VOUCHER_NUMBER
from CRS_T_RES_VOUCHER v, CRS_T_RES_REGISTRATION regi, CRS_T_HTL_PARAMETER para
where v.is_offline_booking = '1' and
TRUNC (SYSDATE) - TRUNC (v.updated_date) > (select TRUNC (para.param_value)
from CRS_T_HTL_PARAMETER para where para.param_key = 'IBE_OFFLINE_CANCELLATION_THRESHOLD')
The reason you are getting the error is that you have two written where clauses twice. Change:
where para.param_key = 'IBE_OFFLINE_CANCELLATION_THRESHOLD'
To:
and para.param_key = 'IBE_OFFLINE_CANCELLATION_THRESHOLD'
According to your last comment, try this:
SELECT v.VOUCHER_NUMBER
FROM CRS_T_RES_VOUCHER v,
CRS_T_RES_REGISTRATION regi,
CRS_T_HTL_PARAMETER para
WHERE v.is_offline_booking = '1'
AND TRUNC (SYSDATE) - TRUNC (v.updated_date) >
(select distinct TRUNC(para.param_value) from CRS_T_HTL_PARAMETER
WHERE para.param_key = 'IBE_OFFLINE_CANCELLATION_THRESHOLD')
Please, note that the query above will work only if there are not several param_values for 'IBE_OFFLINE_CANCELLATION_THRESHOLD' param key.