I have a SQLite table called Price like this:
date, productId, price
----------------------
20120601, 10 , 10.1
20120601, 20 , 20.1
20120602, 10 , 0
20120602, 20 , 0
20120602, 30 , 0
The table is created with this statement:
CREATE TABLE "Price" ("date" INTEGER NOT NULL , "productId" INTEGER NOT NULL , "price" DOUBLE, PRIMARY KEY ("date", "productId"))
I want to fill the price of date==20120602 with the price of the same product in the previous date.
i.e I want the table turn into like this:
date, productId, price
----------------------
20120601, 10 , 10.1
20120601, 20 , 20.1
20120602, 10 , 10.1
20120602, 20 , 20.1
20120602, 30 , 0
So I tried this SQL statement:
UPDATE Price New SET New.price =
(SELECT old.price FROM Price Old WHERE New.date == 2 AND Old.date == 1 AND New.productId == Old.productId)
But SQLite gave me an error near dot.
Than I tried this statement:
UPDATE New Set New.Price = Old.Price
FROM Price New, Price Old
WHRER ......
SQLite gave me an error near FROM.
I double checked SQLite's SQL Syntax but found no lucky. Even I never tried so, I think both statements would work as expected in MS SQL Server. The first statement might work if New and Old are too different tables, but I need them in same table.
I really don't want to write a for loop to update once a line in my C++ code, I need advice on the right way to achieve this in SQLite.
Thank you.
I myself have experienced this. Just remove word New
after UPDATE Price
and wherever you use New.something
change to Price.something
. I am sure there is a much nicer solution, but it works.
updated with code snippet from comments...
UPDATE Price
SET
price = (SELECT old.price FROM Price Old WHERE Old.date = 1 AND price.productId = Old.productId)
WHERE price.date = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With