SQL update only values whose value is not already updated - sql

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

Related

How to insert the result in the desired row? SQL Server

I need the result that I got to be inserted in the right row.
DECLARE #DiscPrice float;
SET #DiscPrice = (SELECT Prod.priceProd - Prod.priceProd / 100 * Prod.disc
FROM Prod
WHERE id_prod = 1);
UPDATE Prod
SET priceDisc = #DiscPrice
WHERE id_prod = 1;
SELECT * FROM Prod;
That is, instead of WHERE id_prod = 1, there was something that inserted the desired result in all rows.
I'm not sure I made myself clear, but I hope that you will understand.
I think you want
UPDATE Prod
SET priceDisc = ((priceProd - priceProd) / 100) * disc
WHERE id_prod = 1;
There is no need to use a variable or a query to assign the value to it.
You can directly update the query as below
UPDATE Prod SET priceDisc =((priceProd - priceProd) / 100 * disc)
This will update the data in all rows

Issue in Selection with CHARINDEX and SUBSTRING

I have 2 questions here.
I have a column 'Campaign' with these entries. My objective is to extract the Cost part from the string and create a new column Cost in my table
29693214 - Live -JUTL Phase 2 Creator Stories Trailer * 7.12 - 7.25 * Video Views * $28,169.01 * BG - Mob
89695072 - Live -WUTL Retargeting JG * 7.16 - 7.31 * Link Clicks * $23,474.18 * KG - Mob
I tried select SUBSTRING(Campaign,CHARINDEX('$',Campaign) +1,???) .I am unable to figure out the '???' part. I want to start with the index next to '$' and continue till the '*' symbol to capture the cost.
While creating a new column I follow these steps
Alter table T ADD NewColumn varchar(100)
then I do this
Update T SET NewColumn = 'Say I want that cost part from the above question here'
Is there any efficient way to do this in single shot?
I think apply makes these operations a bit simpler:
select left(v1.str1, charindex(' ', v1.str1))
from (values ('29693214 - Live -JUTL Phase 2 Creator Stories Trailer * 7.12 - 7.25 * Video Views * $28,169.01 * BG - Mob')) v(str) cross apply
(values (stuff(str, 1, charindex('$', str), ''))) v1(str1);
This can readily be incorporated into an update:
Update t
set newcolumn = left(v.str1, charindex(' ', v.str1))
from t cross apply
(values (stuff(t.str, 1, charindex('$', str), ''))) v(str1)
DDL for testing query:
declare #tbl table(Campaign varchar(200));
insert into #tbl values
('29693214 - Live -JUTL Phase 2 Creator Stories Trailer * 7.12 - 7.25 * Video Views * $28,169.01 * BG - Mob'),
('189695072 - Live -WUTL Retargeting JG * 7.16 - 7.31 * Link Clicks * $23,474.18 * KG - Mob');
If the cost is always separated by a asterisk * from other part of the string, you could use below query:
select trim(substring(Campaign, dollarIndex + 1, asteriskIndex - dollarIndex - 1)) from (
select Campaign, charindex('$', Campaign) dollarIndex,
charindex('*', Campaign, charindex('$', Campaign)) asteriskIndex
from #tbl
) a
To use it in update statement, you could use the same query, but we need to transform above into single query:
update #tbl set Campaign = trim(substring(Campaign, charindex('$', Campaign) + 1, charindex('*', Campaign, charindex('$', Campaign)) - charindex('$', Campaign) - 1))
Note: consider if it's worthy keeping data that you already have (redundancy). If it can be always be parsed from your column in the same way you could use view for this task.
On the other hand it might be qiute expensive to query such data and might be bad for performance.

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.

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

Add a random number between 30 and 300 to an existing field

I have looked on the net as well as here but can't find an answer to the following MySQL question. I'm looking to replace the value of an existing field with a query that has a random number between 30 and 300.
Reason was because I've moved galleries and had 250,000,000 views on my images and there have been lost with the migration and a lot of my members are upset that they have lost views....
UPDATE the_table SET the_field = the_field + FLOOR(RAND() * (270 + 1)) + 30
Use RAND()
UPDATE table
SET field = FLOOR(30 + (RAND() * 270));
WHERE foo = 'bar'
I think this will do the trick:
UPDATE table SET field = ROUND(30 + (RAND() * 270)) WHERE id =1;