Calculate value per day - sql

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.

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

How to write this query compatible with oracle database

I am facing issue to convert the sql query to oracle .Actually i am new to oracle db.
SELECT TI1.FOLDERRSN, DBO.F_OPENTAX_PROPERTYROLL_FOLDER(TI1.FOLDERRSN) ROLL,
TI1.DUEDATE DUEDATE, TI1.YEARFORBILLING,(TI1.SUMDUETAX + TI1.SUMPAIDTAX + TI1.SUMDUEPENALTY + TI1.SUMPAIDPENALTY) OUTSTANDING
FROM TAXINSTALLMENT TI1 WHERE (TI1.SUMDUETAX + TI1.SUMPAIDTAX + TI1.SUMDUEPENALTY + TI1.SUMPAIDPENALTY) > 0
AND EXISTS (SELECT * FROM TAXINSTALLMENT TI2 WHERE YEAR(TI2.DUEDATE) BETWEEN 1980 AND YEAR(GETDATE()) - 5 AND (TI2.SUMDUETAX + TI2.SUMPAIDTAX + TI2.SUMDUEPENALTY + TI2.SUMPAIDPENALTY) > 0
AND TI2.FOLDERRSN = TI1.FOLDERRSN ) ORDER BY TI1.FOLDERRSN, DUEDATE DESC
Anyone give me idea to change to oracle .
Thanks
The statement uses a function F_OPENTAX_PROPERTYROLL_FOLDER(TI1.FOLDERRSN) in Schema DBO. Make sure you have installed that function in that database Schema and have granted an execution right to the user in question or to PUBLIC for that matter.
EDIT: Moreover there is no function YEAR in Oracle. You must replace it with EXTRACT: EXTRACT(YEAR FROM TI2.DUEDATE) and for GetDate(): EXTRACT(YEAR FROM SYSDATE).

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

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);

getting specific index from sql

I'm trying to pull from my sql database without having to load it into a var and pulling the items I want with a for loop.
How can I get the 5 items in the 5th index
" " 5 " " 10th index...
This is what I'm doing not it's way to hackish.
function get_db(a) {
index_count=a
db.transaction(
function(tx) {
var rs = tx.executeSql('SELECT * FROM Greeting');
var r=""
if (up_check === 0){
index_count = index_count +4
}
r += rs.rows.item(index_count).salutation + ": " + rs.rows.item(index_count).salutee + "\t\t"
})
return r
}
I'd ideally want to get something like
var rs = tx.executeSql('SELECT * FROM index_count (and the next for items) Greeting');
If you're SQL Server 2005 or above you can use ROW_NUMBER().
Something like this (freehand):
SELECT *, ROW_NUMBER() OVER(ORDER BY [youordercolumns]) AS [RowNum]
FROM [youtable]
WHERE [RowNum] BETWEEN #index AND #index + 4
It really depends on what Database Server you are using.
For example, MySQL supports a very simple but non-standard solution:
SELECT * FROM Greeting
LIMIT 5 OFFSET yourStartingIndex
Other servers support one or more ways of performing a 'limit with offset'.
The SQL standard provides three ways:
Using OFFSET and FETCH FIRST:(since SQL:2008)
SELECT *
FROM Greeting
OFFSET yourStartingIndex ROWS
FETCH FIRST 5 ROWS ONLY
Using a Window function:(since SQL:2003)
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY YourOrderColumns ASC) AS rownum,
columns
FROM tablename
) AS foo
WHERE rownum > yourStartingIndex AND rownum <= (4+yourStartingIndex)
Using a cursor:
DECLARE cursor-name CURSOR FOR ...
OPEN cursor-name
FETCH RELATIVE number-of-rows-to-skip ...
CLOSE cursor-name
LINKS: http://troels.arvin.dk/db/rdbms/#select-limit-offset