I have a query that inserts a new row and creates a unique date. If there is a conflict, I want to update the row instead.
const updateInsight = await Insight.createQueryBuilder("Insight")
.insert()
.values({ sales: 1 })
.onConflict("(date) DO UPDATE SET sales = sales + 1")
.execute();
This is the same as:
INSERT INTO "Insight" ("sales") VALUES(1) ON CONFLICT (date) DO UPDATE SET sales = sales + 1;
The table looks like this where the date field is default: NOW() with type: Date:
Running the query I get the following error:
"column reference "sales" is ambiguous"
I have tried using Insight.sales = Insight.Sales + 1 in the UPDATE SET, but then I get:
"missing FROM-clause entry for table "insight\
Related
I've done my best to strip down code to bare minimum and provided concise explanation of problem (I hope)
I have a db scheme as indicated below.
def a_method(info_hash)
...
db.execute2 "create table if not exists Table1(Id INTEGER PRIMARY KEY, Item TEXT, Amount FLOAT, Type TEXT, AvgInc FLOAT, AvgX FLOAT, Total FLOAT)"
...
end
This creates my schema. Once I populate the database, I run the following method which gives me the #{#total} value grouped by my Type column:
def get_total(info_hash)
...
get_amt = db.execute2 "SELECT sum(Amount) from Table1 WHERE Type = :Type", info_hash[:category]
puts "foo"
db.execute2 "UPDATE Table1 SET Total = :Total WHERE Type = :Type", get_amt[1][0], info_hash[:category]
#total=get_amt[1][0]
...
#total
end
I want to run the following method to compute an Item average in the event the item did not exist. Basically the impact each Item has on the Type average.
Please see the in code comment for where I think my logic is faulty
def method_excluding(info_hash)
...
get_num = db.execute2 "SELECT Amount from Table1 WHERE Type = :Type", info_hash[:category]
i = 0
get_num.each do |item|
#purpose of block to compute an average value for Type as if #{item} did not exist. So: the average value for Type EXLCUDING #{item}
if i == 1
#avgx = (#total - get_num[1][0]) / i
elsif i > 1
#avgx = (#total - get_num[i][0]) / (i - 1)
end
i+=1
db.execute2 "UPDATE Table1 SET AvgX = :AvgX WHERE Type = :Type", #avgx, info_hash[:category]
...
end
Please advise on how I can get to my desired outcome.
I'm tring to update my mark average by adding to it some value.
My table of admited student contains (NOSTUDENT, COURSECODE, SEMESTER, NOGROUPE,MARK) Columns.
My View : AverageByGroupe contains the average of mark of students following that course in corresponding semester.
CREATE OR REPLACE VIEW AverageByGroup AS
SELECT COURSCODE, NOGROUPE, SEMESTER, AVG(MARK) AS AVGMARK
FROM ADMITED_TABLE GROUP BY COURSECODE,NOGROUPE,SEMESTER;
Question: I want to update the average mark for a given course, group, semester by 10, but AVGMARK is note a column, What it the correct UPDATE syntax.
What I have tried:
UPDATE ADMITED_TABLE
SET AVG(MARK) = SELECT( (AVG(MARK) + 10)
FROM ADMITED_TABLE WHERE COURSCODE = 'AAAA'
AND NOGROUP = 2
AND SEMESTER = 'AUTMN');
Error:
Error de command ligne: 2 Column: 8
Rapport of error -
Erreur SQL : ORA-00927: missing equal sign
00927. 00000 - "missing equal sign"
*Cause:
*Action:
Edit:
To be more clear, this is a mutate table so what I want to use is a INSTEAD OF INSERT TRIGGER wich fire every time the mark average is chaged by adjusting that cours student mark.
For the select syntax error, I included select in (
UPDATE ADMITED_TABLE
SET AVG(MARK) = (SELECT (AVG(MARK) + 10)
FROM ADMITED_TABLE WHERE COURSCODE = 'AAAA'
AND NOGROUP = 2
AND SEMESTER = 'AUTMN');
Error:
ORA-00927: missing equal sign
00927. 00000 - "missing equal sign"
*Cause:
*Action:
UPDATE NewADMITED_TABLE
SET AVGMARK = (AVGMARK + 10) -- this is not a DERIVED column anymore
WHERE COURSCODE = 'AAAA'
AND NOGROUP = 2
AND SEMESTER = 'AUTMN
I have a table where each element is given a order number (numbered 1-50).
I would like to insert a new item after a specified item (usually listed around the 6 or 7 mark) and then update each following element with the new appropriate order number.
For example, I want to insert the new element 'Zoo' after the element "Airport". Here is the list:
- OrderNumber = 1, Name = "Bus Stop"
- OrderNumber = 2, Name = "Dock"
- OrderNumber = 3, Name = "Airport"
- OrderNumber = 4, Name = "Ramp"
- OrderNumber = 5, Name = "Pathway"
After insert of new element:
- OrderNumber = 1, Name = "Bus Stop"
- OrderNumber = 2, Name = "Dock"
- OrderNumber = 3, Name = "Airport"
- OrderNumber = 4, Name = "Zoo"
- OrderNumber = 5, Name = "Ramp"
- OrderNumber = 6, Name = "Pathway"
Notice the order numbers that are updated after inserting the new element "Zoo" in the specified location.
How do I get this to work in SQL?
UPDATE:
I'm using SQL Server Management Studio. And yes, this has to be in SQL.
And to further clarify I asked a more specific and detailed question here that never really got answered: Inserting new row and updating values in SQL
Well, if you know your new value is getting the order number of 4
update <table> set OrderNumber = OrderNumber + 1 where orderNumber >= 4
insert into <table> (ordernumber, Name) values (4, 'Zoo')
EDIT:
On second reading this doesn't really answer you question. What information do you know at the start? Just that 'Zoo' needs to go after 'Airport'?
If that is the case:
declare #to_insert varchar(30) = 'Zoo'
declare #inserted_at varchar(30) = 'Airport'
declare #inserted_at_OrderNumber int
select #inserted_at_ordernumber = ordernumber
from <table>
where name = #inserted_at
insert into <table> (ordernumber,name)
values (#inserted_at_ordernumber, #to_insert)
update <table>
set OrderNumber = OrderNumber + 1
where orderNumber >= #inserted_at_ordernumber
and name <> #to_insert
If you let us know how you would like this to behave we can tailor it a bit better
I am working on Sql Developper an I created the following procedure in a package:
PROCEDURE VALIDER(a_session IN NUMBER) AS
i NUMBER;
TYPE type_tab IS TABLE OF PANIER%ROWTYPE;
tabSeances type_tab;
BEGIN
SELECT * BULK COLLECT INTO tabSeances
FROM PANIER
WHERE a_session = sessionweb;
i:=0;
FOR i IN 1 .. tabSeances.count LOOP
-- UPADTE DU NOMBRE DE PLACES LIBRES
BEGIN
UPDATE PROJECTION
SET remaining_seats = (remaining_seats - tabseances(i).nbrplaces)
WHERE num_copy = tabseances(i).num_copy
AND day = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
COMMIT;
--UPDATE ON PANIER
UPDATE PANIER
SET valide = 1
WHERE sessionweb = a_session
AND num_copy = tabseances(i).num_copy
AND dateseance = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN raise_application_error(-20035, 'Pas de données');
WHEN OTHERS THEN raise_application_error(-20006,'Autres Erreurs');
END;
END LOOP;
END VALIDER;
The procedure executes normaly and I don't get an error.
I have a kind of product cart: "PANIER". I loop all the entries in thsi cart for one person (session) to validate them in the database and decrement the total number of seats.
But the field "remaining-seats" (from PROJECTIONS) in the first update don't work. The field isn't updated. I have already tried with other values but nothing.
I am sure that the procedure is executetd because the second update still works. It marks the cart entry as "CONFIRMED".
I don't have any trigger on this field.
My tables contains valid data (<>NULL).
I execute this procedure like this (in a BEGIN END; block):
CMDPLACES.VALIDER(1);
Thank for your reply.
Is it day or dateseance in your first update?
UPDATE PROJECTION
SET remaining_seats = (remaining_seats - tabseances(i).nbrplaces)
WHERE num_copy = tabseances(i).num_copy
AND dateseance = tabseances(i).dateseance
AND time_slot = tabseances(i).time_slot
AND movie = tabseances(i).movie;
Also as #ThorstenKettner was mentioning, the timestamp data in the date , may fail while comparing, so we have TRUNCATE the timestamp data using TRUNC() [if needed]!
If the date column is indexed, beware the index will not be used by the database .
To handle NO Data in UPDATE, you can check (SQL%ROWCOUNT > 0) to identify the number of rows updated!
Your first update compares days. What data type are these? In case you deal with DATETIME, make sure to compare without the time part if any. Use TRUNC to achieve this.
AND TRUNC(day) = TRUNC(tabseances(i).dateseance)
I am workign with SQL Server 2008 and have to update one field (FIELD_NAM) which contains values of this format:
First value in the field: 'abc', 'efg', 'xyz'
Second value in the field: 'aaaaa', 'bbbb', 'vvvvvv'
I tried with the following statement:
UPDATE Table
SET FIELD = 'ttttt', 'kkkk', 'mmmmmm'
WHERE ID = 1
(only one row and one field/column has to be updated)
The error I got is
Incorrect syntax near 'ttttt'
update "table"
set field = '''ttttt'', ''kkkk'', ''mmmmmm'''
where id = 1
;
UPDATE Table
SET FIELD = 'ttttt\', \'kkkk\', \'mmmmmm'
WHERE ID = 1
OR
UPDATE Table
SET FIELD = 'ttttt'', ''kkkk'', ''mmmmmm'
WHERE ID = 1